1

I need to delete a specific item from a dictonary..

The dictonary is like

      dict["Key1"]="Value1"
      dict["Key2"]="Value2"
      dict["Key3"]="Value3"
      dict["Key4"]="Value2"

How to delete the item if another item has the same value using LINQ

Thanks in advance

Thorin Oakenshield
  • 13,382
  • 31
  • 102
  • 143

4 Answers4

3

check orginal answer by @Jon Skeet : C#: Remove duplicate values from dictionary?

var uniqueValues = myDict.GroupBy(pair => pair.Value)
                         .Select(group => group.First())
                         .ToDictionary(pair => pair.Key, pair => pair.Value);
Community
  • 1
  • 1
Pranay Rana
  • 170,430
  • 35
  • 234
  • 261
3

Here my tested solution:

dict.GroupBy(x => x.Value, x => x.Key)
.Where(x => x.Count() > 1)
.SelectMany(x => x.Skip(1))
.ToList().ForEach(x => dict.Remove(x))
digEmAll
  • 54,872
  • 9
  • 113
  • 136
1
var dupKeys = dict.GroupBy(innerD => innerD.Value)
                .Where(mergedByValue => mergedByValue.Count() > 1)
                .Select(mergedByValue => mergedByValue.OrderByDescending(m => m.Key).First().Key);

dict.Where(d => dupKeys.Contains(d.Key)).ToList()
  .ForEach(d => dict.Remove(d.Key));

This assumes you want the last duplicate removed, where last is defined as the last ordinal string value.

If you want all duplicates removed, change your dupKeys to this:

var dupKeys = dict.GroupBy(innerD => innerD.Value)
                .Where(mergedByValue => mergedByValue.Count() > 1).Dump()
                .SelectMany(mergedByValue => mergedByValue.Select(m => m.Key));
Matt Mitchell
  • 39,515
  • 35
  • 113
  • 182
0

You need to use Distinct.

Incognito
  • 16,327
  • 9
  • 51
  • 72