在C#列表>中,如何提取唯一键/值对并将其存储在List>中?
List<Dictionary<string,string>> md = new List<Dictionary<string,string>>();
md [0]:
[0]:"A","Apple"
[1]:"B","Ball"
md [1]:
[0]:"A","Apple"
[1]:"B","Ball"
MD [2]:
[0]: "C", "Cat"
[1]: "D", "Dog"
md [0]:
[0]:"A","Apple"
[1]:"B","Ball"
MD [1]:
[0]:"C" : "Cat"
[1]:"D" : "Dog"
需要提取两个唯一键/值对的代码示例,不需要唯一键或唯一值。
(*注意:上面的[0],[1]描述了列表和字典中的索引,而不是键或值)
答案 0 :(得分:0)
List<Dictionary<string,string>> md = new List<Dictionary<string,string>>();
var unique = new Dictionary<string, string>();
foreach (var m in md)
{
foreach(var innerKey in m.Key)
{
if (!unique.ContainsKey(innerKey))
{
unique.Add(innerKey, m[innerKey]);
}
}
}
答案 1 :(得分:0)
一种可能的严格正确的解决方案是实施IEqualityComparer<Dictionary<string, string>>
:
public class DictionaryComparer : IEqualityComparer<Dictionary<string, string>>
{
public int GetHashCode(Dictionary<string, string> d)
{
var hashCode = 17;
foreach (var entry in d.OrderBy(kvp => kvp.Key))
{
hashCode = hashCode * 23 + entry.Key.GetHashCode();
hashCode = hashCode * 23 + entry.Value.GetHashCode();
}
return hashCode;
}
public bool Equals(Dictionary<string, string> d1, Dictionary<string, string> d2)
{
string value2;
return d1.Count == d2.Count && d1.All(kvp => d2.TryGetValue(kvp.Key, out value2) && kvp.Value == value2);
}
}
然后获取您的独特词典列表:
var result = md.Distinct(new DictionaryComparer()).ToList();
答案 2 :(得分:-1)
你可以用linq来做。
List<Dictionary<string, string>> md = new List<Dictionary<string, string>>();
md.Add(new Dictionary<string, string>() { { "A","Apple"}, { "B", "Ball" } });
md.Add(new Dictionary<string, string>() { { "A","Apple"}, { "B", "Ball" } });
md.Add(new Dictionary<string, string>() { { "C","Cat"}, { "D", "Dog" } });
var filtered =
md.GroupBy(x => string.Join("", x.Select(i => string.Format("{0}{1}", i.Key, i.Value)))).Select(x => x.First());
变量&#34;过滤&#34;包含具有唯一集的字典列表。