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
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.
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
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly