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
0
: 118 At:- 9/7/2018 8:21:02 AM
C# ASP.NET MVC Drop-down-list






1 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





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