11

If I have a list List<KeyValuePair<string,string>>ex.

["abc","123"]
["asc","123"]
["asdgf","123"]
["abc","123"]

how can I distinc this list?

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
chuckd
  • 13,460
  • 29
  • 152
  • 331

2 Answers2

26

Distinct by both Key and Value:

var results = source.Distinct().ToList();

Distinct by Key or Value (just change the property on GroupBy call:

var results = source.GroupBy(x => x.Key).Select(g => g.First()).ToList();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
-1

You should use a Set (of pair objects) if you wish to have distinct pairs or a Map/Dictionary if you wish to have distinct keys.

Robadob
  • 5,319
  • 2
  • 23
  • 32
  • Does .NET have a proper Set collection? – D.R. Jul 30 '13 at 19:42
  • 2
    `ISet` is the interface, and `HashSet` is an implementation. Works as expected. – Jacob Jul 30 '13 at 19:42
  • The other usual `ISet<>` being `SortedSet<>`. Edit: Although the `SortedSet>` is only useful if given an `IComparer<>` when constructed. – Jeppe Stig Nielsen Jul 30 '13 at 19:51
  • My answer was answering the correct collection type that suits his need (no repeated items), the actual implementation of this collection type would depend on how he's going to use it which we don't know! – Robadob Jul 30 '13 at 19:55