How Do I Sort IList<Class>?
Use OrderBy
Example
public class MyObject()
{
public int number { get; set; }
public string marker { get; set; }
}
IList<MyObject> myobj = new List<MyObject>();
var orderedList = myobj.OrderBy(x => x.marker).ToList();
For a case insensitive you should use a IComparer
public class CaseInsensitiveComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
}
IList<MyObject> myobj = new List<MyObject>();
var orderedList = myobj.OrderBy(x => x.marker, new CaseInsensitiveComparer()).ToList();
I would go against using OrderBy
with a list because it's a LINQ extension method, therefore:
- It wraps the list in an enumerable, then enumerates it and fills a new temporary list, then sorts this new list.
- It wraps the sorted list inside another enumerable.
- Then when you call
ToList()
, it iterates on it and fills another new list with the items.
In essence: it creates and fills 2 new lists and 2 enumerables in addition to the actual sorting.
In comparison, List.Sort()
sorts in place and create nothing so it's way more efficient.
My recommendation would be:
- If you know the underlying type, use
List.Sort()
orArray.Sort(array)
- If you don't know the underlying type, copy the List to a temporary array and sort it using
Array.Sort(array)
and return it.