How can I add new SelectListItem at first position of a List in C# MVC?


I have already created a List in my ASP.NET MVC Controller, now I would like to add new Element at first position of the sorted list, how can I add it using ASP.NET MVC C#?

Here is the current C# code.

public static List<SelectListItem> GetProductLineSelectList()
        {
            Models.CRM.CRMEntities crmdb = new Models.CRM.CRMEntities();

            var productList = (from p in crmdb.E_ProductLine
                               select new SelectListItem { Value = p.ProductLineName, Text = p.ProductLineName }).ToList<SelectListItem>();
 
           //Add new Item at first position in productList

            return productList;
        }

Thanks


Asked by:- manish
1
: 11592 At:- 9/7/2018 8:21:02 AM
C# ASP.NET MVC Drop-down-list







2 Answers
profileImage Answered by:- jaya

You can Simply Add item at the first position of list using .Insert() method

List<T>.Insert(0, item);

Considering your above code, complete solution should like

 public static List<SelectListItem> GetOpportunitySourceSelectList()
        {
            Models.CRM.CRMEntities crmdb = new Models.CRM.CRMEntities();

            var oppList = (from o in crmdb.E_OpportunitySource
                           select new SelectListItem { Value = o.SourceName, Text = o.SourceName }).ToList<SelectListItem>();

            //insert element at first position
            oppList.Insert(0,new SelectListItem() { Value = "YourValue", Text = "Your text" });
            return oppList;
        }

this should work.

2
At:- 9/7/2018 3:32:37 PM
Wasn't aware about .Insert(), thanks 0
By : manish - at :- 9/9/2018 5:50:07 PM


profileImage Answered by:- bhanu

Simply use the below code to add Item at first position

SelectListItem firstItem = new SelectListItem() { Value = "null", Text = "Select One" };

//your list
List<SelectListItem> newList = origList.ToList();

//add item at position 1 using .Insert 
newList.Insert(0, firstItem);

You can also read more about C# List or MVC DropdownListFor on the given links

1
At:- 5/7/2021 11:44:43 AM
.Insert() Works as needed to add item at first Position, thanks. 0
By : pika - at :- 6/3/2022 10:49:18 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use