我有五个字典的类型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