Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>();
}
like image 813
Rye Avatar asked Oct 02 '10 05:10

Rye


1 Answers

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();
like image 180
BrunoLM Avatar answered Oct 13 '22 17:10

BrunoLM