Search code examples
c#winformslinqilist

How Do I Sort IList<Class>?


There's no Sort() function for IList. Can someoene help me with this? I want to sort my own IList.

Suppose this is my IList:

public class MyObject() 
{
 public int number { get; set; }
 public string marker { get; set; }
}

How do I sort myobj using the marker string?

public void SortObject()
{
 IList<MyObject> myobj = new List<MyObject>();
}

Solution

  • 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();