Friday, October 21, 2011

How to find duplicate items in a list of entities by LINQ

I have a list of entities and I need to make sure that all entities have a unique Guid property.

public class FeedDTO
  public string Guid {get; set;}
  public string Name {get; set;}

List<FeedDTO> feeds = GetAllFeeds();

//Case 1:
IEnumerable<string> distinct = feeds.Select(f => f.Guid).Distinct();

//Case 2:
IEnumerable<FeedDTO> distinct = feeds.GroupBy(f => f.Guid).Select(grp => grp.First());

if (feeds.Count != distinct.Count())
   _logger.Info(string.Format("{0} duplicate guid have been detected!",
                feeds.Count - distinctFeeds.Count()));


Post a Comment