开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜