gpt4 book ai didi

c# - 如何使用 LINQ (C# 3.0) 更改 IDictionary 的内容

转载 作者:太空狗 更新时间:2023-10-29 22:29:28 24 4
gpt4 key购买 nike

如何使用 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?

最佳答案

这不像其他方法那么清晰,但它应该可以正常工作:

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);

但这在这种情况下不起作用,因为无法将值分配给。

关于c# - 如何使用 LINQ (C# 3.0) 更改 IDictionary 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/953007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com