Tutorial :LINQ to remove duplicated property



Question:

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?


Solution:1

Use a grouping query:

var media =      from p in postService.GetMedia(postId)      group p by p.SynthId into g      select g.First();  

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 the let keyword:

var media =      from p in postService.GetMedia(postId)      group p by p.SynthId into g      let firstPost = g.First()      select new { PostId = firstPost.PostId, SynthId = firstPost.SynthId };  

If you want all null values for SynthId to be in their own group, then I would probably filter the first list and then do a concatenation, i.e.:

var media = postService.GetMedia(postId);  var myMedia =      (from p in media       where p.SynthId != null       group p by p.SynthId into g       let firstPost = g.First()       select new { PostId = firstPost.PostId, SynthId = firstPost.SynthId })      .Concat      (from p in media       where p.SynthId == null       select new { PostId = firstPost.PostId, SynthId = firstPost.SynthId });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »