1

i've a Dictionary like

Dictionary<String,List<String>> MyDict=new Dictionary<String,List<String>>();

and which contains

{ "One"   { "A", "B", "C" } }
{ "Two"   { "C", "D", "E" } }

Now i need to delele the "C" in "One"

so now MyDict will become

{ "One"   { "A", "B" } }
{ "Two"   { "C", "D", "E" } }

Iterating through the Keyvalue pair and reconstructing the Dictionary will result the required output( Now i'm using this iteration method)

But i s there any way to do this in LINQ?

3
  • What is the condition to determine which instance of C to delete? Commented Nov 3, 2010 at 10:39
  • Its based on the function parameter.(MyFunc(key,item)) Commented Nov 3, 2010 at 10:43
  • Thank you all.......... i was unaware of ` myDict["One"].Remove("C"); ` Commented Nov 3, 2010 at 10:51

3 Answers 3

3

This creates a new dictionary and a new list for each key, omitting the "C" in "One":

var result = myDict.ToDictionary(
    kvp => kvp.Key, 
    kvp => kvp.Value.Where(x => kvp.Key != "One" || x != "C").ToList());

Alternatively, this creates a new dictionary and a new list for "One", keeping the other lists:

var result = myDict.ToDictionary(
    kvp => kvp.Key,
    kvp => (kvp.Key != "One") ? kvp.Value
                              : kvp.Value.Where(x => x != "C").ToList());

It's probably easier and faster to modify the dictionary in-place though:

myDict["One"].Remove("C");
Sign up to request clarification or add additional context in comments.

1 Comment

That should be ||, not &&.
2

LINQ is an overkill here, it's as simple as:

MyDict["One"].Remove("C");

Also LINQ (and functional paradigm as whole) is specifically designed to operate on nonmodfiable sequences, removing something is in general the creation of new sequence which almost always results in huge overhead in this case because it imitates functional paradigm in completely another language.

Comments

0
MyDict["One"].Remove("C");

Why do You want to use linq. One of the features when using LINQ is the immutability of the objects processed so I think this is not what You really want. Doing it with linq is a lot more looooot more complicated (like treating dictionary as a IEnumerable of KeyValuePair then constructing new Dictionary of it....) and probably should not me done unless You are constructing some kind of pipeline processing using this dict.

Comments

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.