Jad*_*ias 5 .net c# linq idictionary c#-3.0
如何使用C#3.0(Linq,Linq扩展)更改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?
Run Code Online (Sandbox Code Playgroud)
这并不像其他方法那么清楚,但它应该可以正常工作:
dictionary.Keys.ToList().ForEach(i => dictionary[i] = 0);
Run Code Online (Sandbox Code Playgroud)
我的另一个选择是制作一个与此类似的 ForEach 扩展方法:
public static class MyExtensions
{
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
dictionary.ForEach(kvp => kvp.Value = 0);
Run Code Online (Sandbox Code Playgroud)
但这在这种情况下不起作用,因为无法分配值。