caesay
caesay

Reputation: 17213

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.

Upvotes: 11

Views: 11761

Answers (3)

pdr
pdr

Reputation: 6440

This should do it, I think

var result = from m in list
             orderby m.Sort, m.Name
             select m;

Upvotes: 4

wsanville
wsanville

Reputation: 37516

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.

Upvotes: 5

tvanfosson
tvanfosson

Reputation: 532465

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

var sorted = list.OrderBy( m => m.Sort ).ThenBy( m => m.Name );

Upvotes: 21

Related Questions