通过事件订购IEnumerable[英] Order IEnumerable by occurrences

本文是小编为大家收集整理的关于通过事件订购IEnumerable的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个来自linq2sql的实体集合(在此阶段已将其列举为数组).该集合可能(可能)包含同一实体的多次出现.我将如何订购该集合,以便最常见的实体被移至正面?

IEnumerable<Entity> results = SearchForEntities(searchCriteria);

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

关于我应该在OrderByDestecending Expression中投入的帮助?

预先感谢! :)

编辑:根据要求澄清.集合中发生的实体不止一次具有唯一的ID,但不是对同一对象的引用.

推荐答案

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

问题是:该集合包含多个实体具有相同的ID ,还是实际上有多个引用对相同实体对象?

如果第一个情况(通过ID),您可能需要此:

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

其他推荐答案

尝试以下方法:

IEnumerable<Entity> results = SearchForEntities(searchCriteria);

return results.OrderByDescending(e => results.Where(a=>a == e).Count())
          .Distinct()
          .Take(maxSearchResults);

本文地址:https://www.itbaoku.cn/post/1556965.html

问题描述

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);

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

Thanks in advance! :)

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);

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

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);

其他推荐答案

Try this:

IEnumerable<Entity> results = SearchForEntities(searchCriteria);

return results.OrderByDescending(e => results.Where(a=>a == e).Count())
          .Distinct()
          .Take(maxSearchResults);