按属性/匿名函数对列表进行排序?

发布于 2024-09-26 22:16:43 字数 219 浏览 0 评论 0原文

我有一个这样定义的列表...

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

为什么没有重载,以便我可以像这样对其进行排序?

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

我首先想要最大的一组。最简单的方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最单纯的乌龟 2024-10-03 22:16:43

因为 List 类是在 .NET 2.0 中引入的,并且该类的设计者决定这样做。您可以使用 OrderByDescending< /a> 扩展方法:

sets = sets.OrderByDescending(s => s.Count).ToList();

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();
秋意浓 2024-10-03 22:16:43

试试这个:

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

这使用了 List.SortSort(ComparisonComparison) 重载。
该表达式将 B 与 A 进行比较,而不是 A 与 B 进行比较,这一事实会产生您所需的按计数降序排列。

您的代码不起作用的原因是 List.SortEnumerable.OrderByDescending 不同,它没有接受 Func 键选择器。

@Darin Dimitrov 使用 OrderByDescending 的技术也很好,但请注意,这会创建一个不合适的排序列表,并将您对原始列表的引用重新分配给新的排序列表。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文