简体   繁体   中英

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 is there any way to do this in LINQ?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM