Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to get the results from another LINQ collection

Tags:

c#

linq

I have a LINQ statement which pulls the top N record IDs from a collection and then another query which pulls all records which have those IDs. It feels very clunky and inefficient and i was wondering if there might be a more succinct, LINQy way to get the same results

var records = cache.Select(rec => rec.Id).Distinct().Take(n);

var results = cache.Where(rec => records.Contains(rec.Id));

FYI - there will be multiple records with the same ID, which is why there is the Distinct() and why i can't use a simple Take() in the first place.

Thanks!

like image 459
Josh Avatar asked Feb 08 '10 23:02

Josh


2 Answers

How about something like this?

var results = cache.GroupBy(rec => rec.Id, rec => rec)
                   .Take(n)
                   .SelectMany(rec => rec);
like image 198
LukeH Avatar answered Oct 23 '22 21:10

LukeH


The same thing you did, but in one line and with Join() instead of Contains():

var results = cache
    .Select(rec => rec.Id)
    .Distinct()
    .Take(n)
    .ToList()
    .Join(cache, rec => rec, record => record.Id, (rec, record) => record);
like image 38
Boris Lipschitz Avatar answered Oct 23 '22 23:10

Boris Lipschitz