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

1
  • 1
    Which item do you want to delete, the item with Key2 or the one with Key4? Commented Jun 30, 2010 at 6:41

4 Answers 4

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))
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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));

Comments

0

You need to use Distinct.

5 Comments

@ Incognito: Thank you... you are correct but i need to remove the duplicates after creating the dictonary.
& Pramodh, You are not correct, distinct will not help you filter a collection based on a property of the objects and still use associated properties.
Have you checked the link. This is not SQL distinct. You can use it on existing dictionary.
yes? now try and use it to get the keys of all distinct values.
@Graphain I agree it gives you way to get distinct values easily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.