Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a List by a property and then by another

I have an example class containing two data points:

public enum Sort { First, Second, Third, Fourth }
public class MyClass
{
    public MyClass(Sort sort, string name) { 
        this.Sort = sort; 
        this.Name = name; 
    }

    public Sort Sort { get; set; }
    public string Name { get; set; }
}

I'm looking to sort them into groups by their Sort property, and then alphabetize those groups.

List<MyClass> list = new List<MyClass>() { 
    new MyClass(MyClass.Sort.Third, "B"), 
    new MyClass(MyClass.Sort.First, "D"),
    new MyClass(MyClass.Sort.First, "A"),
    new MyClass(MyClass.Sort.Fourth, "C"),
    new MyClass(MyClass.Sort.First, "AB"),
    new MyClass(MyClass.Sort.Second, "Z"),
};

The output would then be: (showing Name)

A
AB
D
Z
B
C

I've been able to do this by using a foreach to separate the items into many smaller arrays (grouped by the enum value) but this seems very tedious - and I think there must be some LINQ solution that I don't know about.

like image 534
caesay Avatar asked Mar 10 '10 02:03

caesay


People also ask

How do you sort a list of objects by some properties?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.

Can you sort a list C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.

How do you sort collections in C#?

Sort(IComparer) This method is used to sort the elements in the entire ArrayList using the specified comparer. This method is an O(n log n) operation, where n is Count; in the worst case, it is an O(n^2) operation. Syntax: public virtual void Sort (IComparer comparer);


2 Answers

Using extension methods, first OrderBy the enum, ThenBy name.

var sorted = list.OrderBy( m => m.Sort ).ThenBy( m => m.Name );
like image 101
tvanfosson Avatar answered Sep 25 '22 07:09

tvanfosson


Aside from the nice LINQ solutions, you can also do this with a compare method like you mentioned. Make MyClass implement the IComparable interface, with a CompareTo method like:

  public int CompareTo(object obj)
  {
      MyClass other = (MyClass)obj;
      int sort = this.srt.CompareTo(other.srt);
      return (sort == 0) ? this.Name.CompareTo(other.Name) : sort;
  }

The above method will order your objects first by the enum, and if the enum values are equal, it compares the name. Then, just call list.Sort() and it will output the correct order.

like image 20
wsanville Avatar answered Sep 24 '22 07:09

wsanville