Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 1st, 2012  |  syntax: None  |  size: 0.88 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Use Linq to construct distinct, ordered of objects based on properties
  2. class Foo()
  3. {
  4.     public Bar [] bars;
  5. }
  6.  
  7. class Bar ()
  8. {
  9.     public string name;
  10.     public int id;
  11. }
  12.        
  13. foo[0] => bars { { name = "one", id = 1 }, { name = "two", id = 2 }, { name = "three", id = 3 },
  14. foo[1] => bars { { name = "four", id = 4 }, { name = "four", id = 4 }
  15.        
  16. { name = "one", id = 1 }, { name = "two", id = 2 }, { name = "three", id = 3 }, { name = "four", id = 4 }
  17.        
  18. var values = foo.SelectMany(f => f.bars)
  19.                 .Distinct()
  20.                 .OrderBy(b => b.id);
  21.        
  22. var values = foo.SelectMany(f => f.bars)
  23.                 .DistinctBy(b => b.id)
  24.                 .OrderBy(b => b.id);
  25.        
  26. var values = foo.SelectMany(f => f.bars)
  27.                 .DistinctBy(b => new { b.id, b.name })
  28.                 .OrderBy(b => b.id);
  29.        
  30. Foos.SelectMany(foo => foo.bars).OrderBy(bar => bar.id).Distinct()