【问题标题】:Incorrectly making new collection from existing collections错误地从现有收藏中创建新收藏
【发布时间】:2014-05-11 02:24:22
【问题描述】:

我仍然是 C# 的初学者,所以我确信我在这里遗漏了一些基本概念,但我正在为此苦苦挣扎。
我正在尝试从两个现有集合中创建一个新集合。
第一个是Dictionary<string, someModel[]>
第二个是Dictionary<string, string>
我试图找到两个字典键之间的匹配项,如果它们匹配,则使用两个字典中的值创建一个新的myOtherModel,但如果它们不匹配,我仍然想创建一个新的myOtherModel,但使用一个空字符串对于缺少的值,然后添加所有这些新的 myOtherModel 将被添加到列表中。
新的 myModel 对象将是两种情况之一
例如:Dict1.Keys = 1,2,3,4....100。 Dict2.Keys = 5,9,27,55

myList.Add(new myModel = {1, "", someModel[]}) //did not find a match 
myList.Add(new myModel = {5, dict2.MatchingValue, someModel[]}) // did find a match

所以基本上,比较两个字典,对于较大字典中的每个项目,使用项目的值创建一个新的 myModel(其中一个将为空)。但是,如果该项目的键与另一个字典中的键匹配,则获取第二个字典的值并将其添加到新的 myModel
我试着弄乱一个元组,但我无法按照我想要的方式操纵它们。

这是我到目前为止所拥有的,但我没有给我 490 个项目(来自 dict1 的计数),而是得到了 44k(两者相乘的数量)

foreach (var pair in dict1)
        {
            foreach (var item in dict2)
            {
                if (item.Key == pair.Key)
                {
                    var x = new myModel()
                    {
                        prop1 = item.Value,
                        prop2 = pair.Key,
                        prop3 = pair.Value
                    }; 
                    myListOfModels.add(x);

                }
                else
                {
                    var x = new myModel()
                    {
                        prop1 = "",
                        prop2 = pair.Key,
                        prop3 = pair.Value
                    };
                  myListOfModels.add(x);
                }
            }
        }

【问题讨论】:

    标签: c# dictionary collections


    【解决方案1】:

    每次遍历第一个集合时,您都会遍历第二个集合,这就是您看到太多结果的原因。您可以使用简单的 Linq 轻松简化您的代码...

        foreach (var pair in dict1)
        {
            // Get the matched value.  If there isn't one it should return the default value for a string.
            var matchedValue = dict2.Where(x => x.Key == pair.Key).Select(x => x.Value).SingleOrDefault();
            var x = new myModel()
            {
                prop1 = matchedValue,
                prop2 = pair.Key,
                prop3 = pair.Value
            };
            myListOfModels.add(x);
        }
    

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2013-08-02
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多