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 nestedgroupby
, value select 1 want. here usedfirstordefault
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
Post a Comment