重置保留键的 .NET 字典

moo*_*kid 2 .net containers c#-3.0

我有一Dictionary<K,V>组已知的、不变的键。我想重置字典,但保留键的值,仅将值更改为null.

我可以先调用Clear()字典并重新添加对null作为值,应该有更好的方法。

Ham*_*jam 5

您可以使用键并将所有值设置为 null

例如

var d = new Dictionary<int, string>();
d.Keys.ToList().ForEach(x => d[x] = null);
Run Code Online (Sandbox Code Playgroud)

这是您可以使用的扩展方法列表,选择哪些套件更适合您的情况并测试它们的性能

public static class DictionaryExtensions
{
    public static Dictionary<K, V> ResetValues<K, V>(this Dictionary<K, V> dic)
    {
        dic.Keys.ToList().ForEach(x => dic[x] = default(V));
        return dic;
    }

    public static Dictionary<K,V> ResetValuesWithNewDictionary<K, V>(this Dictionary<K, V> dic)
    {
        return dic.ToDictionary(x => x.Key, x => default(V), dic.Comparer);
    }

}
Run Code Online (Sandbox Code Playgroud)

并像使用它一样

var d = new Dictionary<int, string>();
d.ResetValues().Select(..../*method chaining is supported*/);
Run Code Online (Sandbox Code Playgroud)

或者

d = d.ResetValuesWithNewDictionary().Select(..../*method chaining is supported*/);
Run Code Online (Sandbox Code Playgroud)