Convert from List<Dictionary<DateTime, Points[]>> to Dictionary<DateTime, Points[]>

use*_*222 2 c# .net-core

I have List<Dictionary<DateTime, Points[]>> taskResult generated from tasks

var taskResult = tasks.Select(t => t.Result).ToList();
var data = new Dictionary<DateTime, Points[]>();
Run Code Online (Sandbox Code Playgroud)

in my function I want to return Dictionary<DateTime, Points[]> data but I cant figure out how to do that. I tried using foreach but had no luck

Fab*_*bio 8

Enumerable.SelectMany extension method is right tool for the job, which combines many collections into one. Dictionary is a collection of key-value pairs.

var combined = dictionaries
    .SelectMany(dictionary => dictionary.Select(pair => pair))
    .GroupBy(pair => pair.Key)
    .ToDictionary(
        group => group.Key, 
        group => group.SelectMany(pair => pair.Value).ToArray());
Run Code Online (Sandbox Code Playgroud)

Approach above will merge points of same date if original dictionaries contain duplicated dates

Because Dictionary implements IEnumerable you can remove .Select in first call of SelectMany.
Alternative for .GroupBy is .ToLookup method, which can have multiple values per one key.

var combined = dictionaries
    .SelectMany(dictionary => dictionary)
    .ToLookup(pair => pair.Key, pair.Value)
    .ToDictionary(
        lookup => lookup.Key, 
        lookup => lookup.SelectMany(points => points).ToArray());
Run Code Online (Sandbox Code Playgroud)