Sorting an IList using LINQ
posted by Bryan on
We have a custom object called ListOption in our code. It holds category, value and option and fairly represents the basics of a single SelectList item. To hold the ListOption values, the primary developer stored this List as and IList instead of an ArrayList or any other concrete type. OptionList extends IEnumerable
Here is how I sorted the IList.
//The ListOption object. Simple.
public class ListOption
{
public String category;
public String value;
public String option;
public ListOption(String category, String value, String option)
{
//set values here - removed
}
//others methods here
}
Using LINQ, I was able to sort the list quickly using the OrderBy function. Since ListOption.option is the text displayed, this was the value I wanted to sort on.
//snippet from OptionList : IEnumerable<ListOption>
private IList<ListOption> optionList = new List<ListOption>();
public void Sort()
{
IEnumerable<ListOption> sortedEnum = optionList.OrderBy(f => f.option);
optionList = sortedEnum.ToList();
}