问题
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