c# - How to Join two dictionary collections linq query -


my first data collection this:

ienumerable<dictionary<string, object>> firstsourcedata; 

items this:

new dictionary<string, object> {     ["id"] = 1,     ["name"] = "some",     ["age"] = 30 } 

and second data dictionary collection:

ienumerable<dictionary<string, object>> secondsourcedata; 

items this:

new dictionary<string, object> {     ["id"] = 1,     ["sales"] = 58,     ["age"] = 30 } 

these 2 data comes different sources , create single dictionary collection not contain duplicated values. id key standart dictianaries , other properties may change.

ienumerable<dictionary<string, object>> joined;  new dictionary<string, object> {     ["id"] = 1,     ["sales"] = 58,     ["name"] = "some",     ["age"] = 30 }, 

how can linq lambda expressions? (and there problem if sources length difference)

this looking do:

  • merge 2 collections of dictionaries.
  • group items "id" key-value.
  • for each group have multiple dictionaries use selectmany flatten , groupby on key. can recreate dictionaries - todictionary. notice might have keys repeating why nested groupby , value select 1 want. here used firstordefault

so:

var result = firstsourcedata.concat(secondsourcedata)                 .groupby(item => item["id"])                 .select(group => group.selectmany(item => item)                                       .groupby(item => item.key)                                       .todictionary(key => key.key,                                                      value => value.firstordefault().value)); 

this result:

new dictionary<string, object> {     ["id"] = 1,     ["sales"] = 58,     ["name"] = "some",     ["age"] = 30 }, new dictionary<string, object> {     ["id"] = 2,     ["sales"] = 58,     ["age"] = 30 } 

for test case:

var firstsourcedata = new list<dictionary<string, object>> {     new dictionary<string, object>     {         ["id"] = 1,         ["sales"] = 58,         ["age"] = 30     },     new dictionary<string, object>     {         ["id"] = 2,         ["sales"] = 58,         ["age"] = 30     } };  var secondsourcedata = new list<dictionary<string, object>> {     new dictionary<string, object>     {         ["id"] = 1,         ["name"] = "some",         ["age"] = 30     } }; 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -