订购IEnumerable by [英] Order IEnumerable by occurrences

查看:73
本文介绍了订购IEnumerable by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自Linq2Sql的可枚举的实体集合(在此阶段它们已被枚举为数组).该集合可能(可能会)包含同一实体的多次出现.我该如何对集合进行排序,以便将最常出现的实体移到最前面?

I have an enumerable collection of entities which have come from Linq2Sql (they have been enumerated to an array by this stage). The collection may (probably will) contain multiple occurrences of the same entity. How would I go about ordering the collection so that entities which occurred most often are moved to the front?

IEnumerable<Entity> results = SearchForEntities(searchCriteria);

return results.OrderByDescending(e => /* Number of occurences in results? */)
              .Distinct()
              .Take(maxSearchResults);

对我应该在OrderByDescending表达式中添加的内容有任何帮助吗?

Any help on what I should be putting in the OrderByDescending expression?

提前谢谢! :)

根据要求进行澄清.集合中多次出现的实体具有唯一的ID,但不是对同一对象的引用.

edit: Clarification as requested. The entities which occur in the collection more than once have a unique id, but are not references to the same object.

推荐答案

return results.GroupBy(r => r)
              .OrderByDescending(g => g.Count())
              .Select(g => g.Key)
              .Take(maxSearchResults);

问题是:集合中是否包含具有相同ID 的多个实体,或者实际上存在对同一实体对象的多个引用?

The question is: does the collection contain multiple entities with the same ID or are there actually multiple references to the same entity object?

如果是第一种情况(按ID),则可能需要这样做:

If the first one is the case (by ID), you may want this:

return results.GroupBy(r => r.ID)
              .OrderByDescending(g => g.Count())
              .Select(g => g.First())
              .Take(maxSearchResults);

这篇关于订购IEnumerable by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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