code_junkie

LINQy way to check if any objects in a collection have the same property value

Nov 12th, 2011
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. var duplicates = agents.GroupBy(a => a.ID).Where(a=>a.Count() > 1);
  2.  
  3. foreach (var agent in duplicates)
  4. {
  5. Console.WriteLine(agent.Key.ToString());
  6. }
  7.  
  8. public class Foo
  9. {
  10. public int ID;
  11. }
  12.  
  13. var list = new List<Foo>();
  14.  
  15. var r = new Random();
  16.  
  17. for (int i = 0; i < 10000; i++) list.Add(new Foo { ID = r.Next() });
  18.  
  19. var sw = new Stopwatch();
  20. sw.Start();
  21. bool b = list.Any(i => list.Where(j => i != j).Any(j => j.ID == i.ID));
  22. Console.WriteLine(b);
  23. Console.WriteLine(sw.ElapsedTicks);
  24.  
  25. sw.Reset();
  26. sw.Start();
  27. b = (list.GroupBy(i => i.ID).Count() != list.Count);
  28. Console.WriteLine(b);
  29. Console.WriteLine(sw.ElapsedTicks);
  30.  
  31. foreach(var agent in Agents) {
  32. if(Agents.Count(a => a.ID == agent.ID) > 1)
  33. Console.WriteLine("Found: {0}", agent.ID);
  34. }
  35.  
  36. bool b = list.Any(i => list.Any(j => j.ID == i.ID && j != i));
  37.  
  38. var duplicates = agents
  39. .GroupBy(a => a.ID)
  40. .Where(g => g.Skip(1).Any());
Add Comment
Please, Sign In to add comment