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
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.
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.
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().
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With