[英]C# List<Dictionary<string,string>> - how to extract unique key/value pairs
在C#List>中,如何提取唯一的鍵/值對並將其存儲在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]表示列表和字典中的索引,而不是鍵或值)
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]);
}
}
}
一種可能完全正確的解決方案是實現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();
您可以使用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());
變量“已過濾”包含具有唯一集合的詞典列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.