Order IEnumerable by occurrences

纵饮孤独 提交于 2019-12-13 19:14:50

问题


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.


回答1:


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



回答2:


Try this:

IEnumerable<Entity> results = SearchForEntities(searchCriteria);

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


来源:https://stackoverflow.com/questions/5583734/order-ienumerable-by-occurrences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!