performance - How do I convert this nested foreach to linq C# -
when tried convert nested foreach linq, i'm unable it. have tried of several ways nothing. didn't result these foreach
foreach (string field in extractorresults.keys) { if (fileresults.containskey(field)) { foreach (extractionresult exresult in extractorresults[field]) { fileresults[field].add(exresult); } } else fileresults.add(field, extractorresults[field]); } }
seems trying 'merge' 2 dictionaries:
fileresults = fileresults.concat(extractorresults) .groupby(kvp => kvp.key) .todictionary(g => g.key, g => g.selectmany(kvp => kvp.value).tolist()); explanation:
- get keyvaluepairs both dictionaries
- group keyvaluepairs keys
- create new dictionary contain entry each group - same key , list of values selected grouped keyvaluepairs. can add
distinct()call after selecting values if don't want duplications in result. though original foreach-based logic produces duplicates.
step step (i'll use json format show data flow):
assume have 2 dictionaries following data (actual data types not matter here):
fileresults = [ { key:"a", value: [1,2] }, { key: "b", value: [5] } ]; extractorresults = [ { key:"c", value: [7] }, { key: "b", value: [3,4] } ]; after concatenating these dictionaries single sequence of key value pairs
[ { key:"a", value: [1,2] }, { key: "b", value: [5] }, { key:"c", value: [7] }, { key: "b", value: [3,4] } ] next goes grouping:
[ { key: "a", items: [ { key:"a", value: [1,2] } ] }, { key: "b", items: [ { key: "b", value: [5] }, { key: "b", value: [3,4] }, { key: "c", items: [ { key:"c", value: [7] } ] ] and create new dictionary entries each group above:
[ { key: "a", value: [1, 2] }, { key: "b", value: [5, 3, 4] }, { key: "c", value: [7] } ]
Comments
Post a Comment