简体   繁体   中英

C# List<Dictionary<string,string>> - how to extract unique key/value pairs

In a C# List>, how can I extract unique key/value pairs and store it in List>?

List<Dictionary<string,string>> md = new List<Dictionary<string,string>>();

Input

md[0] :

[0]:"A","Apple"
[1]:"B","Ball"

md[1]:

[0]:"A","Apple"
[1]:"B","Ball"

md[2]:

[0]: "C", "Cat"
[1]: "D", "Dog"

Output

md[0] :

[0]:"A","Apple"
[1]:"B","Ball"

md[1]:

[0]:"C" : "Cat"
[1]:"D" : "Dog"

Code sample to extract both unique key/value pairs are needed, only unique keys or unique values are not needed.

(* Note : [0],[1] above depicts the indexes in the list and dictionary and not the keys or values)

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]);
      }
    }
}

One possible strictly correct solution would be to implement 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);
    }
}

Then to get your list of unique dictionaries:

var result = md.Distinct(new DictionaryComparer()).ToList();

You can do it with 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());

Variable "filtered" contains list of dictionaries with unique sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM