Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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[]>();

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

like image 619
user122222 Avatar asked Feb 20 '26 04:02

user122222


1 Answers

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());

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());
like image 127
Fabio Avatar answered Feb 22 '26 18:02

Fabio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!