0

Here is my list of KeyValuePairs

List<KeyValuePair<string,string>> kvpair =new List<KeyValuePair<string,string>>()
sample data

    "the brown fox", "xy the brown fox...."
    "the brown Fox", "xy the brown Fox...."
    "The brown Fox", "xy the brown Fox...."
    "the brown fox", "xy the brown fox...."
    "the brown fox", "xy the brown fox...."
    "The black fox", "xy The black fox...."

As you can see there are too many duplicate records in the list. How can I skip all duplicates and get kvpair with only distict keys along with its corresponding value from the list. My expected result should contain only two records (ie., expected result should be as follows

"the brown Fox", "xy the brown Fox...."  
"The black fox", "xy The black fox...."

)

I tried this, but not working as expected

var distinctKvPair=kvPair.Where(g => g.Key.Contains(g.Key, StringComparison.OrdinalIgnoreCase)).GroupBy(g=>g.Key) as List<KeyValuePair<string, string>>
Progman
  • 16,827
  • 6
  • 33
  • 48
roney
  • 964
  • 3
  • 15
  • 37
  • Why should the key `"the brown Fox"` be chosen and not any other key like `"the brown fox"` (which comes first). – Progman Apr 14 '22 at 19:02
  • 1
    Does this answer your question? [Case-INsensitive Dictionary with string key-type in C#](https://stackoverflow.com/questions/13988643/case-insensitive-dictionary-with-string-key-type-in-c-sharp) – Progman Apr 14 '22 at 19:04
  • In net6 you have DistinctBy, eg `kvps.DistinctBy(kvp => kvp.ToLower())`. In older you can do same with GroupBy: `kvps.GroupBy(kvp => kvp.ToLower(), (k,g) => g.First())` – Caius Jard Apr 14 '22 at 19:26
  • @Progman , case doesn't matter, it can be the firstordefault – roney Apr 14 '22 at 19:53

0 Answers0