2

List
I need to filter this list.
I just want to have those person that have the same SalId and those must be at least two.

How do I do it?

ekad
  • 14,436
  • 26
  • 44
  • 46
Don Juan
  • 171
  • 2
  • 17
  • 1
    see [group by clause](http://msdn.microsoft.com/ru-ru/library/bb384063.aspx) and `select` where count in group >= 2 – Grundy Nov 29 '13 at 13:18

1 Answers1

9
var dupSalIdPersons = persons
  .GroupBy(p => p.SalId)
  .Where(g => g.Count() >= 2)
  .SelectMany(g =>  g);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • tim, i'm sure you've got a timemachine going there. speedy responese -+1 – jim tollan Nov 29 '13 at 13:21
  • @user1083647: note that you can use `.Select(g => g.ToList()).ToList();` instead of `.SelectMany(g => g);` if you want a `List>` instead where each list contains all duplicate persons. My approach above flattens all persons into a single collection which is currently unordered. – Tim Schmelter Nov 29 '13 at 13:24
  • @TimSchmelter What would happen if there's `.Select(g => g.First()).ToList();` instead of `SelectMany(g => g);` because I saw many ppl are working with `.First()).ToList()` when they want to get rid of duplicates columns – Roxy'Pro May 07 '20 at 11:25
  • @Roxy'Pro: that's a completly different requirement. This question didnt want to remove duplicates, Don Juan wanted to list all persns with at least two equal `SalId`. The `g.First()` approach removes those duplicates whereas mine approach above lists them. – Tim Schmelter May 07 '20 at 13:36