根据组计数排序列表 [英] Sort list based on group count

查看:149
本文介绍了根据组计数排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 IGrouping s的元素计数上的 List



就是这样,理想情况下列表应该是相同的。我会妥协一个新的列表,但然后这些元素应该是相同的原始对象,而不是复制品(无论是浅的)还是绝对不是匿名的对象。



具体来说:我们有一个具有许多属性的实体和一个这种类型的对象列表。我们希望(1)按特定属性(名称,地址,...)对对象进行分组,然后(2)计算每个组中的元素数量。最后,我们希望(3)通过将首先放入较大组的元素的元素重新排序列表。



注意:我们的主要问题是,我们似乎无法找到一种方法来保留对组中元素中的原始对象的引用。事实上,我们可以在Linq查询中选择的是分组键(或键的属性),而且没有任何内容由 IGrouping 公开。我们无法弄清楚如何将组元素与列表中的元素关联起来,而不需要查看数据(即使这样,我们也需要主键,我们不能将其添加到分组键中,或者它会击败分组的目的开始)。

解决方案

  var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count())
.SelectMany(x => x).ToList();


I'd like to sort a List on element counts of IGroupings.

And that's it, the list should ideally be the same. I would compromise with a new list, but then the elements should be the very same original objects, not copies (however shallow) and definitely not anonymous objects.

Specifically: We have an entity with many properties, and a list of objects of this type. We'd like to (1) group the objects by certain properties (name, address, ...) then (2) count the number of elements in each group. Finally we'd like to (3) reorder the list based on these counts by placing the elements that are part of the larger groups first.

Note: Our main issue is that we can't seem to find a way to keep a reference to the original objects in the elements of the groups. Indeed all we can select in the Linq query is the grouping key (or properties of the key) and nothing else is exposed by IGrouping. We can't figure out how to associate a group element with an element of the list either, short of looking at the data (and even then, we'd need the primary key, which we can't add to the grouping key or it would defeat the purpose of the grouping to begin with).

解决方案

var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count())
                       .SelectMany(x => x).ToList();

这篇关于根据组计数排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆