我有五個字典的類型Dictionary<ThingId, Thing>
和Dictionary<ThingId, List<Thing>>
。我想對所有的人都遍歷的規則如下:迭代幾個字典的聯合
- 迭代上的所有ThingId不重複
- 對於每個鍵(又名每個ID),得到的東西從所有詞典列表而不將它們混合(它們不具有相同的功能含義)。
現在,我這樣做:
void DoSomething(Dictionary<ThingId, Thing> dic1, Dictionary<ThingId, List<Thing>> dic2, Dictionary<ThingId, List<Thing>> dic3) // only 3 to not clutter the code
{
var ids = new HashSet<ThingId>(dic1.Keys).AddRange(dic2.Keys).AddRange(dic3.Keys);
foreach (var id in ids)
{
Thing thing1;
List<Thing> things2;
List<Thing> things3;
if (!dic1.TryGetValue(id, out thing1)
{
//default
thing1 = new Thing(id);
}
if (!dic2.TryGetValue(id, out things2)
{
//default
things2 = new List<Thing>();
}
if (!dic3.TryGetValue(id, out things3)
{
//default
things3 = new List<Thing>();
}
DoSomethingElse(thing1, things2, things3);
}
}
是否有可能與Linq
做到這一點?例如,做一個字典鍵的聯合,並從值中創建匿名類(需要時使用「默認」值)?
我看着Union
方法,但它不是我想要的。
我不太瞭解linq union,但也許你可以使用AsParalell()來改善itteration performan CE? – thanatorr