Sort a List by a property and then by another
Solution 1
Using extension methods, first OrderBy
the enum, ThenBy
name.
var sorted = list.OrderBy( m => m.Sort ).ThenBy( m => m.Name );
Solution 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.
Solution 3
This should do it, I think
var result = from m in list
orderby m.Sort, m.Name
select m;
caesay
I'm in a committed relationship with good code, so if we go out it will only be as friends. Feel free to contact me by email at mk.stackexchange<a>caesay.com
Updated on June 05, 2022Comments
-
caesay almost 2 years
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. -
Ahmad Mageed about 14 yearsThis syntax is not valid. The
select m
needs to be placed at the end, then it'll be correct.