How to get unique values ​​from two dictionary lists using Linq?

This is my code.

public class Model
{
    public Model();

    public Dictionary<string, string> Data { get; set; }

}

list<dictionary<string,string>>  data1;
list<dictionary<string,string>>  data2;

data1=await get<model>();
data2=await get<model>();

data1[0]=[0][{id,101}]
         [1][{name,one}]
         [2][{marks,56}]
         [3][{state,ap}]     

data1[1]=[0][{id,102}]
         [1][{name,two}]
         [2][{marks,65}]
         [3][{state,up}]     

data1[2]=[0][{id,103}]
         [1][{name,three}]
         [2][{marks,89}]
         [3][{state,usa}]     



data2[0]=[0][{roleid,101}]
         [1][{stdname,one}]
data2[1]=[0][{roleid,102}]
         [1][{stdname,two}]

Finally I want Output Like

data3[0]=[0][{id,103}]
         [1][{name,three}]
         [2][{marks,89}]
         [3][{state,usa}]     

in the code above, I have two lists of dictionaries, I want the unqiue id values ​​to be compared with two lists. In the two lists above, the key names are different, except for the values ​​from the two lists based on the identifier of the first list and the second list.

+4
source share
2 answers

Assuming you want to cross into lists:

Use the intersection method. First make a comparison between the two dictionaries:

public class DictComparer : IEqualityComparer<Dictionary<string, string>>
{
    public bool Equals(Dictionary<string, string> x, Dictionary<string, string> y)
    {
        return (x == y) || (x.Count == y.Count && !x.Except(y).Any());
    }

    public int GetHashCode(Dictionary<string, string> x)
    {
        var ret = 123;
        foreach (var keyValue in x)
        {
            ret = ret + (keyValue.GetHashCode() * 31);
        }
        return ret;
    }
}

Then use it as follows:

var result = data1.Union(data2).Except(data1.Intersect(data2, new DictComparer()), new DictComparer());

: , . . Edit2: GetHashCode . , , :

+2

,

public class DictComparerById : IEqualityComparer<Dictionary<string, string>>
{
    public bool Equals(Dictionary<string, string> x, Dictionary<string, string> y)
    {
        // Two dictionary are equal if the have the same "id"
        string idX;
        if(!x.TryGetValue("id", out idX))
            x.TryGetValue("roleid", out idX);

        string idY;
        if(!y.TryGetValue("id", out idY))
            y.TryGetValue("roleid", out idY);

        return (idX == idY);
    }

    public int GetHashCode(Dictionary<string, string> x)
    {
        string id;
        if(!x.TryGetValue("id", out id))
            x.TryGetValue("roleid", out id);
        return id.GetHashCode();
    }
}

var dictCmp = new DictComparerById();
var data3 = data1
    .Union(data2, dictCmp)
    .Except(data1.Intersect(data2, dictCmp), dictCmp);
+2

Source: https://habr.com/ru/post/1609617/


All Articles