c# - How to get unique values from two list of dictionaries using Linq? -


this 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 want output like

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

in above code have 2 list of dictionaries, want unqiue id values compare 2 lists.the above 2 lists key names different except values 2 lists based on first list id , second list roleid.

assuming intersect lists:

use intersect method. first implement comparer between 2 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 this:

var result = data1.union(data2).except(data1.intersect(data2, new dictcomparer()), new dictcomparer()); 

edit: noticed wanted exact opposite. changed function accordingly. edit2: missing proper implementation of gethashcode dictionaries. implementation seems work: link


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -