Sort a List by a property and then by another

2020-08-17 07:56发布

问题:

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.

回答1:

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

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


回答2:

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.



回答3:

This should do it, I think

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