Reputation: 7412
I often find myself doing the below to extract properties from a list of objects just to create an aggregated list. How would this be expressed with LINQ?
var totalErrors =
new Dictionary<string, string>();
foreach (var res in results)
{
foreach (var err in res.Errors)
{
totalErrors
.Add(err.Key, err.Value);
}
}
return totalErrors;
Upvotes: 0
Views: 162
Reputation: 984
You can use SelectMany :
var allErrors = Results.SelectMany( res=>res.Errors );
//foreach( var error in allErrors )...
var dictionary = allErrors.ToDictionary( x=>x.Key, x=> x.Value );
Upvotes: 0
Reputation: 26635
You can use SelectMany
and ToDictionary
methods:
var result = results
.SelectMany(x => x.Errors) // get all Errors in one sequence
.ToDictionary(x => x.Key, x => x.Value); // create new dictionary based on this Enumerable
SelectMany()
projects each element of a sequence to an IEnumerable<T>
and flattens the resulting sequences into one sequence. And ToDictionary()
creates a Dictionary<TKey, TValue>
from an IEnumerable<T>
according to a specified key selector function.
Upvotes: 2
Reputation: 726579
You can do an aggregation on two levels with SelectMany
, like this:
var totalErrors = results
.SelectMany(r => r.Errors)
.ToDictionary(e => e.Key, e => e.Value);
SelectMany
"flattens" a collection of collections into a single level, at which point you can apply ToDictionary
to a flattened list.
Upvotes: 1