Thorin Oakenshield
Thorin Oakenshield

Reputation: 14682

How to delete a value from the dictionary in C# using linq?

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?

Upvotes: 1

Views: 2667

Answers (3)

luckyluke
luckyluke

Reputation: 1563

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.

Upvotes: 0

dtb
dtb

Reputation: 217303

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

Upvotes: 3

Grozz
Grozz

Reputation: 8425

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.

Upvotes: 2

Related Questions