tags:

views:

87

answers:

4

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

A: 

You need to use Distinct.

Incognito
@ Incognito: Thank you... you are correct but i need to remove the duplicates after creating the dictonary.
Pramodh
Graphain
Have you checked the link. This is not SQL distinct. You can use it on existing dictionary.
Incognito
@Incognito, yes? now try and use it to get the keys of all distinct values.
Graphain
@Graphain I agree it gives you way to get distinct values easily.
Incognito
+3  A: 

check orginal answer by @Jon Skeet : http://stackoverflow.com/questions/1462101/c-remove-duplicate-values-from-dictionary

var uniqueValues = myDict.GroupBy(pair => pair.Value)
                         .Select(group => group.First())
                         .ToDictionary(pair => pair.Key, pair => pair.Value);
Pranay Rana
+1  A: 
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));
Graphain
+3  A: 

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
This answer is actually clever. Didn't know about the GroupBy that takes a "select this" parameter.
Graphain