如何使用LINQ过滤字典并将其返回相同类型的字典 [英] How can I filter a dictionary using LINQ and return it to a dictionary from the same type
本文介绍了如何使用LINQ过滤字典并将其返回相同类型的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字典:
Dictionary<int,string> dic = new Dictionary<int,string>();
dic[1] = "A";
dic[2] = "B";
我想过滤字典中的项目并将结果重新分配给相同的变量:
I want to filter the dictionary's items and reassign the result to the same variable:
dic = dic.Where (p => p.Key == 1);
如何以相同类型[<int,string>
]的字典形式返回结果?
How can I return the result as a dictionary from the same type [<int,string>
] ?
我尝试了ToDictionary
,但是没有用.
I tried ToDictionary
, but it doesn't work.
提前谢谢.
推荐答案
ToDictionary
是解决方法.它确实起作用-您可能是错误地使用了它.试试这个:
ToDictionary
is the way to go. It does work - you were just using it incorrectly, presumably. Try this:
dic = dic.Where(p => p.Key == 1)
.ToDictionary(p => p.Key, p => p.Value);
话虽如此,我假设您真的想要一个不同的Where
过滤器,因为您当前的过滤器只会找到一个键...
Having said that, I assume you really want a different Where
filter, as your current one will only ever find one key...
这篇关于如何使用LINQ过滤字典并将其返回相同类型的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文