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
  • 14,232
  • 33
  • 106
  • 146

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
  • 175,020
  • 35
  • 237
  • 263
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
  • 56,430
  • 9
  • 115
  • 140
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
  • 40,943
  • 35
  • 118
  • 185
0

You need to use Distinct.

Incognito
  • 16,567
  • 9
  • 52
  • 74