如何使用 C# 3.0 (Linq, Linq extensions) 更改 IDictionary 的内容?
var enumerable = new int [] { 1, 2};
var dictionary = enumerable.ToDictionary(a=>a,a=>0);
//some code
//now I want to change all values to 1 without recreating the dictionary
//how it is done?
如何使用 C# 3.0 (Linq, Linq extensions) 更改 IDictionary 的内容?
var enumerable = new int [] { 1, 2};
var dictionary = enumerable.ToDictionary(a=>a,a=>0);
//some code
//now I want to change all values to 1 without recreating the dictionary
//how it is done?
LINQ 是一种查询方言——它不是直接的变异语言。
要更改现有字典的值,foreach
可能是您的朋友:
foreach(int key in dictionary.Keys) {
dictionary[key] = 1;
}
这不像其他方式那么清楚,但它应该可以正常工作:
dictionary.Keys.ToList().ForEach(i => dictionary[i] = 0);
我的另一种选择是制作类似于此的 ForEach 扩展方法:
public static class MyExtensions
{
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
}
然后像这样使用它:
dictionary.ForEach(kvp => kvp.Value = 0);
但是,这在这种情况下不起作用,因为无法将 Value 分配给。
foreach (var item in dictionary.Keys)
dictionary[item] = 1;
不过,我想知道为什么您可能需要做这样的事情。