Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way of splitting a C# generic dictionary into multiple dictionaries?

I have a C# dictionary Dictionary<MyKey, MyValue> and I want to split this into a collection of Dictionary<MyKey, MyValue>, based on MyKey.KeyType. KeyType is an enumeration.

Then I would be left with a dictionary containing key-value pairs where MyKey.KeyType = 1, and another dictionary where MyKey.KeyType = 2, and so on.

Is there a nice way of doing this, such as using Linq?

like image 614
Fiona - myaccessible.website Avatar asked Feb 01 '10 15:02

Fiona - myaccessible.website


People also ask

Can you split an air conditioner?

If your home does not have ductwork, a split air conditioner is a good option since you will not incur the additional cost of having ductwork installed in every room. The single system works well within a small area providing adequate heating or cooling.

How can I split my air conditioner into two rooms?

Vent between the two rooms using a top vent (one near the ceiling) and a lower vent (near the floor). Also a fan at the lower vent forcing the air from the air conditioned room to the non-air conditioned room.

Can one split system cool two rooms?

A multi split-air conditioner is a type of split air conditioner. While a split air conditioner cools only one room at a time, a multi-split air conditioner lets you cool multiple rooms at a time.

Can we use one AC in two rooms?

Normally one indoor unit should be used for one room only, since each room has different needs. Also, people who live in two different rooms might have different comfort needs. This way the operating setting of the unit might satisfy the needs of the one room, but not of the second.


2 Answers

var dictionaryList = 
    myDic.GroupBy(pair => pair.Key.KeyType)
         .OrderBy(gr => gr.Key)  // sorts the resulting list by "KeyType"
         .Select(gr => gr.ToDictionary(item => item.Key, item => item.Value))
         .ToList(); // Get a list of dictionaries out of that

If you want a dictionary of dictionaries keyed by "KeyType" in the end, the approach is similar:

var dictionaryOfDictionaries = 
    myDic.GroupBy(pair => pair.Key.KeyType)
         .ToDictionary(gr => gr.Key,         // key of the outer dictionary
             gr => gr.ToDictionary(item => item.Key,  // key of inner dictionary
                                   item => item.Value)); // value
like image 140
mmx Avatar answered Nov 14 '22 23:11

mmx


I believe the following will work?

dictionary
    .GroupBy(pair => pair.Key.KeyType)
    .Select(group => group.ToDictionary(pair => pair.Key, pair => pair.Value);
like image 39
Sam Harwell Avatar answered Nov 14 '22 23:11

Sam Harwell