Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group into a dictionary of elements

Tags:

c#

linq

group-by

Hi I have a list of element of class type class1 as show below. How do I group them into a

Dictionary<int,List<SampleClass>> based on the groupID

class SampleClass
{
   public int groupID;
   public string someData;
 }                                                                                  

I have done this way:

var t =(from data in datas group data by data.groupID into dataGroups select dataGroups).ToDictionary(gdc => gdc.ToList()[0].groupID, gdc => gdc.ToList());

Is there a better way of doing thiss

like image 377
Subodh Chettri Avatar asked Mar 24 '11 04:03

Subodh Chettri


People also ask

How do you enter an element into a dictionary?

To add user input to a dictionary in Python:Declare a variable that stores an empty dictionary. Use a range to iterate N times. On each iteration, prompt the user for input. Add the key-value pair to the dictionary.

What is a dictionary element?

An element is a substance that cannot be separated into simpler substances through chemistry. An element is also an important component of something or a natural habitat. Element has many other senses as a noun. In chemistry, an element is something that cannot be broken down any further.

How do you group dictionary using keys?

Method : Using sorted() + items() + defaultdict() The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted().

Can you index into a dictionary?

You can find a dict index by counting into the dict. keys() with a loop. If you use the enumerate() function, it will generate the index values automatically.


1 Answers

It will be more efficient to replace:

gdc => gdc.ToList()[0].groupID

with:

gdc => gdc.Key

Other than that, it looks like I would have done.

Alternately, if you are okay with extension methods over LINQ (I personally prefer them), it can be shortened further still with:

var t = data.GroupBy(data => data.groupID).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
like image 181
DocMax Avatar answered Oct 19 '22 23:10

DocMax