[英]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" 现在我需要删除“一个”中的“ C”
so now MyDict
will become 所以现在MyDict
将成为
{ "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) 遍历Keyvalue对并重建Dictionary将产生所需的输出(现在我正在使用此迭代方法)
But is there any way to do this in LINQ? 但是在LINQ中有什么方法可以做到这一点吗?
This creates a new dictionary and a new list for each key, omitting the "C" in "One": 这将为每个键创建一个新字典和一个新列表,在“一个”中省略“ C”:
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: LINQ在这里是一个过大的杀伤力,它很简单:
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. LINQ(和整个功能范式)也经过特殊设计,可在不可修改的序列上运行,通常,删除某些内容会创建新的序列,在这种情况下几乎总是会产生巨大的开销,因为它完全用另一种语言模仿了功能范式。
MyDict["One"].Remove("C");
Why do You want to use linq. 为什么要使用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. 使用LINQ的功能之一是处理对象的不变性,所以我认为这不是您真正想要的。 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. 使用linq进行操作要复杂得多(例如将字典作为KeyValuePair的IEnumerable然后将其构造成新的Dictionary ....),除非您正在使用此dict构造某种管道处理,否则可能不应该这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.