Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list by property/anonymous function?

I've got a list defined like this...

var sets = new List<HashSet<int>>(numSets);

Why isn't there an overload so I can sort it like this?

sets.Sort(s => s.Count);

I want the largest set first. What's the easiest way to do that?

like image 444
mpen Avatar asked Jun 08 '26 22:06

mpen


2 Answers

Because List<T> class was introduced in .NET 2.0 and the designers of this class decided so. You could use the OrderByDescending extension method:

sets = sets.OrderByDescending(s => s.Count).ToList();
like image 115
Darin Dimitrov Avatar answered Jun 10 '26 16:06

Darin Dimitrov


Try this:

sets.Sort((setA, setB) => setB.Count.CompareTo(setA.Count));

This uses the Sort(Comparison<T> comparison) overload of List<T>.Sort. The fact that the expression compares B with A rather than A with B is what produces the descending-by-count order that you require.

The reason your code doesn't work is because List<T>.Sort, unlike Enumerable.OrderByDescending, does not have an overload that accepts a Func<TSource, TKey> key-selector.

@Darin Dimitrov's technique of using OrderByDescending is fine too, but note that this will create a sorted list out of place and reassign the reference you have to the original list to the new, sorted one.

like image 27
Ani Avatar answered Jun 10 '26 16:06

Ani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!