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!
How about something like this?
var results = cache.GroupBy(rec => rec.Id, rec => rec)
.Take(n)
.SelectMany(rec => rec);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With