Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 不正确地从现有集合创建新集合_C#_Dictionary_Collections - Fatal编程技术网

C# 不正确地从现有集合创建新集合

C# 不正确地从现有集合创建新集合,c#,dictionary,collections,C#,Dictionary,Collections,我仍然是C#的初学者,因此我确信我在这里遗漏了一些基本概念,但我正在努力解决这个问题。 我正在尝试从两个现有收藏中创建一个新收藏。 第一个是词典 第二个是词典 我试图在两个dicts键之间找到匹配项,如果它们与两个dicts中的值匹配,则生成一个新的myOtherModel,但如果它们不匹配,我仍然希望生成新的myOtherModel,但缺少值的字符串为空,然后添加所有新的myOtherModel将添加到列表中。 新的myModel对象将是两种方案之一 例如:Dict1.Keys=1,2,3,4

我仍然是C#的初学者,因此我确信我在这里遗漏了一些基本概念,但我正在努力解决这个问题。
我正在尝试从两个现有收藏中创建一个新收藏。
第一个是
词典

第二个是
词典

我试图在两个dicts键之间找到匹配项,如果它们与两个dicts中的值匹配,则生成一个新的
myOtherModel
,但如果它们不匹配,我仍然希望生成新的
myOtherModel
,但缺少值的字符串为空,然后添加所有新的
myOtherModel
将添加到列表中。
新的myModel对象将是两种方案之一
例如:Dict1.Keys=1,2,3,4…100。Dict2.键=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(两个项目相乘的数量)


每次迭代第一个集合时,您都在循环第二个集合,这就是您看到太多结果的原因。您可以通过简单的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);
    }
    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);
    }