0

我一直在努力寻找合并或合并两个 dics 的逻辑..

enum type
{
 First,
 Second,
 Third
}

Class sample
{
 string name;
 int no;
}
public static Dictionary<type,List<sample>> GetDataDir(Dictionary<type,List<sample>> data1,Dictionary<type,List<sample>> data2)
{
   Dictionary<type,List<sample>> dataOut = new Dictionary<type,List<sample>>();
   // here one of the sample instance (data1) and key name is equal condition ,we have to update the data1 dic with key and update the sample of data2
   return dataOut ;
}

请帮我找到出路...

4

1 回答 1

1

我想这就是你所追求的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    internal enum sampleEnum
    {
        a,
        b,
        c,
        d
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            var a = new Dictionary<sampleEnum, sampleValue>();
            var b = new Dictionary<sampleEnum, sampleValue>();

            a.Add(sampleEnum.a, new sampleValue());
            a.Add(sampleEnum.b, new sampleValue());

            b.Add(sampleEnum.a, new sampleValue());
            b.Add(sampleEnum.b, new sampleValue());
            b.Add(sampleEnum.c, new sampleValue());
            b.Add(sampleEnum.d, new sampleValue());

            // Add missing b values into a
            foreach (var objItem in from l2 in b where !a.ContainsKey(l2.Key) select l2)
            {
                a.Add(objItem.Key, objItem.Value);
            }

            // Merge b's values into a
            foreach (var objItem in from l2 in b where a.ContainsKey(l2.Key) select l2)
            {
                a[objItem.Key] = objItem.Value;
            }

            System.Diagnostics.Debug.Assert(true);
        }
    }

    internal class sampleValue
    {
    }
}
于 2013-02-19T11:37:49.607 回答