我有五本Dictionary<ThingId, Thing>和Dictionary<ThingId, List<Thing>>类型的字典。我想用以下规则对所有这些规则进行迭代:
现在,我这样做:
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方法,但它不是我想要的。
发布于 2017-10-12 09:49:43
就性能而言,这种方法效率很低,但是对于Linq:
void DoSomething(Dictionary<ThingId, Thing> dic1, Dictionary<ThingId, List<Thing>> dic2, Dictionary<ThingId, List<Thing>> dic3) // only 3 to not clutter the code
{
dic1.Keys.Union(dic2.Keys).Union(dic3.Keys).Distinct().ToList().ForEach(id =>
DoSomethingElse(
dic1.FirstOrDefault(d => d.Key == id).Value ?? new Thing(id),
dic2.FirstOrDefault(d => d.Key == id).Value ?? new List<Thing>(),
dic3.FirstOrDefault(d => d.Key == id).Value ?? new List<Thing>())
);
}另一种方法是扩展字典,然后使用该扩展:
public static class DictionaryExtension
{
public static VType GetSafeValue<KType, VType>(this Dictionary<KType, VType> dic, KType key) where VType : class
{
VType v;
if (!dic.TryGetValue(key, out v))
{
return null;
}
return v;
}
}那你就可以用
dic1.Keys.Union(dic2.Keys).Union(dic3.Keys).Distinct().ToList().ForEach(id =>
DoSomethingElse(
dic1.GetSafeValue(id) ?? new Thing(id),
dic2.GetSafeValue(id) ?? new List<Thing>(),
dic3.GetSafeValue(id) ?? new List<Thing>())
);https://stackoverflow.com/questions/46706223
复制相似问题