我有
Dictionary<string, List<int>> myDict = new Dictionary<string, List<int>>();
在某些时候,我想为特定的字典关键字添加数字到myDict。
我目前正在做
if (!myDict.ContainsKey(newKey)){
myDict[newKey] = new List<int>();
}
myDict[newKey].Add(myNumber);
但这似乎容易出错,有时甚至会忘记ContainsKey检查。
我一直在寻找一种方法,使myDict [“ entry”]尚不存在的情况下,使Dictionary返回一个新列表,但我找不到任何东西。
参考方案
这是我提到的LazyLookup
示例的相对简单的实现。它只是出于简洁/简洁的目的实施IEnumerable
来回答问题。
本质上,在访问索引时,它将确保已将其初始化为List<T>
类的新实例。
public class LazyLookup<TKey, TValue> : IEnumerable<List<TValue>>
{
private readonly Dictionary<TKey, List<TValue>> CachedEntries;
private readonly Func<List<TValue>> LazyListCreator;
public LazyLookup()
: this(() => new List<TValue>())
{
}
public LazyLookup(Func<List<TValue>> lazyListCreator)
{
this.LazyListCreator = lazyListCreator;
this.CachedEntries = new Dictionary<TKey, List<TValue>>();
}
public List<TValue> this[TKey key]
{
get
{
return GetOrCreateValue(key);
}
}
private List<TValue> GetOrCreateValue(TKey key)
{
List<TValue> returnValue;
if (!CachedEntries.TryGetValue(key, out returnValue))
{
returnValue = LazyListCreator();
CachedEntries[key] = returnValue;
}
return returnValue;
}
public IEnumerator<List<TValue>> GetEnumerator()
{
return CachedEntries.Values.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
有一些用法:
var lazyLookup = new LazyLookup<string, int>();
lazyLookup["nocheck"].Add(9001);
//outputs 9001
Console.WriteLine(lazyLookup["nocheck"][0]);
//outputs 0 as it's a newly initialized list
Console.WriteLine(lazyLookup["someOtherLookup"].Count);
此时,您可以将其更新为线程安全的(因为GetOrCreateValue
当前不是线程安全的),或对其进行泛化,以使其不假定它为List<T>
的任何类型,或者将其扩展为实现完整的IDictionary<TKey, TValue>
接口。但是至少,如果您经常使用上面发布的上述模式,则可以考虑将字典的直接用法与某些封装互换,从而使您的工作变得琐碎并消除了代码重复。
我的代码段List<List<optionsSort>> stocks = new List<List<optionsSort>>(); optionsSort tempStock1 = new optionsSort(); List<optionsSort> stock = new List<…
C#等效于Java List <?扩展类> - c#我有泛型类的基本结构public class Parent<T> where T : Parent<T> { Action<T> Notify; } public class Child : Parent<Child> { } 我想要一个列表,以便可以将Child对象放在此处List<Parent>…
将List <List <string >>转换为List <string> - c#This question already has answers here: Closed 9 years ago. Possible Duplicate: Linq: List of lists to a long list我已经使用LINQ进行了转换。List<List<string>>至List<string>.如…
List <Dog>是List <Animal>的子类吗?为什么Java泛型不是隐式多态的? - java我对Java泛型如何处理继承/多态感到困惑。假设以下层次结构-动物(父母)狗-猫(儿童)因此,假设我有一个方法doSomething(List<Animal> animals)。根据继承和多态性的所有规则,我假设List<Dog>是List<Animal>,而List<Cat>是List<Animal&g…
将谓词<T>转换为Func <T,bool> - c#我有一个包含成员Predicate的类,希望在Linq表达式中使用该类:using System.Linq; class MyClass { public bool DoAllHaveSomeProperty() { return m_instrumentList.All(m_filterExpression); } private IEnumerable&…