nik
nik

Reputation: 1784

Combining multiple dictionary where key matches

I get a

Dictionary<DateTime,double>() 

from different part of an application. This can return a number of dictionaries which is why I store them in a list:

var masterlist = new List<Dictionary<DateTime, double>>();

I would like to combine the dictionaries now where the DateTime key is equal and turn the result into an array object[,] so that each row looks like this:

DateTime, double_d1, double_d2, ... double_dn

where d1, d2, ..., dn is mock code for the dictionaries in the list. how can I do this please?

Upvotes: 1

Views: 159

Answers (4)

Perfect28
Perfect28

Reputation: 11317

You can try this :

    Dictionary<DateTime, double[]> preResult = masterlist.SelectMany(s => s).GroupBy(k => k.Key)
        .ToDictionary(k => k.Key, v => v.Select(s => s.Value).ToArray());

   var result = preResult.Select(s =>
    {
        var res = new List<object>(); 

        res.Add(s.Key);
        res.AddRange(s.Value.Cast<object>());

        return res.ToArray(); 

    }).ToArray();

Upvotes: 4

bcl
bcl

Reputation: 167

How about this:

        Dictionary<DateTime, List<double>> result =
        masterlist.Select(x => x.AsEnumerable())
            .Aggregate((a, b) => a.Concat(b))
            .GroupBy(x => x.Key)
            .ToDictionary(k => k.Key, v => v.Select(x => x.Value).ToList());

Upvotes: 0

Miłosz Wieczorek
Miłosz Wieczorek

Reputation: 591

Here is similar solution to @Ksv3n, where the result is the Dictionary of DateTime as key and List of doubles as value:

Dictionary<DateTime, List<double>> masterDic = masterlist 
    .SelectMany(dic => dic)
    .GroupBy(dic => dic.Key)
    .ToDictionary(dic => dic.Key, values => values.Select(v => v.Value).ToList());

Upvotes: 2

Chetan
Chetan

Reputation: 6901

You can use Dictionary<DateTime, List<double>>. You loop thru the list of dictionary you have and add entries in to this dictionary.

var masterlist = new List<Dictionary<DateTime, double>>();

Dictionary<DateTime, List<double>> dtDoubles = new Dictionary<DateTime, List<double>>();
foreach (var item in masterlist)
{
    foreach (var kvPair in item)
    {
        if (!dtDoubles.ContainsKey(kvPair.Key))
        {
            dtDoubles.Add(kvPair.Key, new List<double> {kvPair.Value});
        }
        else
        {
            dtDoubles[kvPair.Key].Add(kvPair.Value);
        }
    }
}

Upvotes: 0

Related Questions