sprocket12
sprocket12

Reputation: 5488

How to convert this into a dictionary of a dictionary

How do I change this to : Dictionary<string, Dictionary<DateTime, double>>

var data = segGroups.Join(pPeriods, s => s.segid, p => p.entid, (s, p) => new
            {
                Name = s.SegCode, // string
                Time = p.StartLocal, // datetime
                TR = p.Volume // double
            })
            .GroupBy(s => s.Name)
            .ToList();

The string will be the Name, and the internal dictionary will be the DateTime and TR pairs.

Upvotes: 2

Views: 119

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You don't have to call ToList() before ToDictionary unless you're really using that list somewhere else:

var data = segGroups.Join(pPeriods, s => s.segid, p => p.entid, (s, p) => new
                    {
                        Name = s.SegCode, // string
                        Time = p.StartLocal, // datetime
                        TR = p.Volume // double
                    })
                    .GroupBy(s => s.Name)
                    .ToDictionary(g => g.Key, g => g.ToDictionary(i => i.Time, i => i.TR));

data will be typed into Dictionary<string, Dictionary<DateTime, double>>.

You also have to be sure that Time within each group is unique. ArgumentException will be thrown otherwise, because two items in Dictionary can't have the same Key.

Upvotes: 0

Servy
Servy

Reputation: 203820

var dictionary = data.ToDictionary(group => group.Key, 
    group => group.ToDictionary(item => item.Time, item => item.TR));

Note that there is no casting going on here. Casting is treating something as something else, without changing what it really is. This is converting the list into the dictionary by creating an entirely new object that is simply based on some other value. It's an important distinction.

Upvotes: 5

Related Questions