我想在词典列表中选择条目,以便创建仅包含我所需的不同项目的新词典。
例如,从此列表开始:
List<Dictionary<string, string>> test = new List<Dictionary<string, string>>{
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret B"}, {"idtGroupe", "idtLivretB"}, {"variables", "test2"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret B"}, {"idtGroupe", "idtLivretB"}, {"variables", "test2"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret B"}, {"idtGroupe", "idtLivretB"}, {"variables", "test2"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
new Dictionary<string, string>{{"labelGroup", "Livret A"}, {"idtGroupe", "idtLivretA"}, {"variables", "test1"}},
};
我想有一本不带键“变量”的新字典,其中包含:
{"labelGroup", "Livret A"},
{"idtGroupe", "idtLivretA"},
{"labelGroup", "Livret B"},
{"idtGroupe", "idtLivretB"}
答案 0 :(得分:1)
上面的答案很好,但是您可以使用一个简单的衬纸来完成。
var distincts = test.SelectMany(x => x).Where(x=> x.Key != "variables").Distinct();
SelectMany()将从您的词典中选择所有项目,然后加入一本词典
Distinct()-简单的一个,它将选择不同的项目
答案 1 :(得分:0)
您可以使用Distinct()
方法。您必须在字典列表中迭代每个键。您的输出必须是字典列表,否则您将遇到重复的密钥问题。
var distinctDictionary = new List<Dictionary<string, string>>();
foreach (var keyItem in test.First().Keys)
{
if (keyItem == "variables")
continue;
var tempDistinct = (from t in test select t[keyItem]).Distinct();
foreach (var distinctItem in tempDistinct)
{
distinctDictionary.Add(new Dictionary<string, string>() { { keyItem, distinctItem } });
}
}
如果测试词典为空,则First()
方法将引发异常。您可能需要在迭代之前检查它是否为空。