c#从List创建字典

本文关键字:创建 字典 Dictionary List | 更新日期: 2023-09-27 18:07:45

我有一个字典列表,如:

dic1.Add("A_key1","A_val11"); dic1.Add("B_key1","B_val11")
dic1.Add("C","C"); dic1.Add("D","D");
dic2.Add("A_key1","A_val21");  dic1.Add("B_key1","B_val21");
dic2.Add("C","C");  dic1.Add("D","D");
dic2.Add("A_key2","A_val22");  dic1.Add("B_key2","B_val22");
dic2.Add("A_key3","A_val23");  dic1.Add("B_key3","B_val23");
List<Dictionary<string,string>> tempList = new List<Dictionary<string,string>>{dic1, dic2};

我需要从tempList创建一个字典遵循规则:key = "A_key*"值,val = "B_key*"值从列表中的所有原始字典。在上面的例子中:

expectDic = {("A_val11","B_val11"),
              ("A_val21","A_val21"),
              ("A_val22","A_val22"),
              ("A_val23","A_val23")}

我可以用Linq解决吗?

c#从List<Dictionary>创建字典

你的问题不清楚,所以我要做一些假设。如果这些假设不正确,请告诉我,我会适当地修改。

离开您的测试数据,因为键是相同的,合并字典将是不可能的,因此列表。

最后,你的测试数据本身是不正确的,因为它抛出一个异常。因此,我假设测试数据如下:

        Dictionary<string, string> dic1 = new Dictionary<string, string>();
        Dictionary<string, string> dic2 = new Dictionary<string, string>();
        dic1.Add("A_1", "A_val11");
        dic1.Add("B_1", "B_val11");
        dic1.Add("C", "C");
        dic1.Add("D", "D");

        dic2.Add("A_1", "A_val21");
        dic2.Add("A_2", "A_val22");
        dic2.Add("A_3", "A_val23");
        dic2.Add("B_1", "B_val21");
        dic2.Add("B_2", "B_val22");
        dic2.Add("B_3", "B_val23");
        dic2.Add("C", "C");
        dic2.Add("D", "D");

        List<Dictionary<string, string>> tempList = new List<Dictionary<string, string>> { dic1, dic2 };

下面是一些代码,将为给定的例子工作:

Dictionary<string, string> expectDic = new Dictionary<string, string>();
        for (int i = 0; i < tempList.Count; i++)
        {
            Dictionary<string, string> onedic = tempList[i];
            while (onedic.Values.ToList().Where(x => x.Contains("A_")).FirstOrDefault() != null)
            {
                expectDic.Add(onedic.Select(x => x.Value).Where(x => x.Contains("A_") && !expectDic.Keys.Contains(x)).First(), onedic.Select(x => x.Value).Where(x => x.Contains("B_") && !expectDic.Values.Contains(x)).First());
                onedic.Remove(onedic.Select(x => x.Key).Where(x => x.Contains("A_")).FirstOrDefault());
                onedic.Remove(onedic.Select(x => x.Key).Where(x => x.Contains("B_")).FirstOrDefault());
            }
        }

然而,你要求的是非常复杂的,我建议对LINQ进行异常处理。