我在寻找稍微不同的问题的解决方案时发现了这篇文章,但使用公认的答案作为我的解决方案的基础,所以我认为有同样问题的人也可能会走这条路。
我正在寻找一种方法来在一组对象中找到单个属性,该属性在每个对象的属性集中都是唯一的。我在字典中有属性名称,我想要一个只出现在一个字典中的键列表。
这是我的解决方案,您应该可以将其粘贴到 linqpad 中以查看它是否正常工作。
void Main()
{
var d = new Dictionary<string, Dictionary<string, string>>
{
{
"First",
new Dictionary<string, string>
{
{"A", "ash"},
{"B", "brett"},
{"R", "ripley"},
{"J", "jones"},
{"D", "dallas"}
}
},
{
"Second",
new Dictionary<string, string>
{
{"A", "ash"},
{"B", "brett"},
{"R", "ripley"},
{"D", "dallas"},
{"K", "kane"}
}
},
{
"Third",
new Dictionary<string, string>
{
{"A", "ash"},
{"B", "brett"},
{"R", "ripley"},
{"D", "dallas"},
{"V", "vasquez"}
}
},
{
"Fourth",
new Dictionary<string, string>
{
{"A", "ash"},
{"B", "brett"},
{"R", "ripley"},
{"D", "dallas"},
{"H", "hicks"}
}
}
};
var u = d.Values.SelectMany(x => x.Keys).Distinct().Where(y => d.Values.SelectMany(z => z.Keys).Count(a => a == y) == 1).ToArray();
foreach (var f in u)
{
Console.WriteLine("{0} => {1}", f, d.Keys.Single(s => ((Dictionary<string, string>)d[s]).ContainsKey(f)));
}
}