首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >几个字典合并的迭代

几个字典合并的迭代
EN

Stack Overflow用户
提问于 2017-10-12 09:37:28
回答 1查看 70关注 0票数 0

我有五本Dictionary<ThingId, Thing>Dictionary<ThingId, List<Thing>>类型的字典。我想用以下规则对所有这些规则进行迭代:

  1. 在所有ThingId上迭代而不重复
  2. 对于每个键(也就是每个Id),从所有字典()中获取事物列表,而不将它们混合为(它们没有相同的功能含义)。

现在,我这样做:

代码语言:javascript
复制
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方法,但它不是我想要的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-12 09:49:43

就性能而言,这种方法效率很低,但是对于Linq:

代码语言:javascript
复制
    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>())
        );
    }

另一种方法是扩展字典,然后使用该扩展:

代码语言:javascript
复制
    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;
        }
    }

那你就可以用

代码语言:javascript
复制
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>())
        );
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46706223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档