I have a LINQ statement like this:
var media = (from p in postService.GetMedia(postId)
select new
{
PostId = postId,
SynthId = p.SynthId
});
There are many(possibly thousands) of records returned with the same SynthId. I want to select one one, any random one. So when I’m finished, media should contain records with distinct SynthId.
SynthId can be null, I want all nulls to be in media (the distinct should not affect them).
My DAL is EntityFramework, if that will help.
How do I accomplish this in the most efficient way?
Use a grouping query:
This will give you the first post in the sequence for each group of records, where the grouping key is the
SynthId.If it’s important for you to do a projection (i.e. to use
select new { ... }) then you should be able to use theletkeyword:If you want all
nullvalues forSynthIdto be in their own group, then I would probably filter the first list and then do a concatenation, i.e.: