I have the following code :
using System.Collections.Generic;
public class Test
{
static void Main()
{
var items = new List<KeyValuePair<int, User>>
{
new KeyValuePair<int, User>(1, new User {FirstName = "Name1"}),
new KeyValuePair<int, User>(1, new User {FirstName = "Name2"}),
new KeyValuePair<int, User>(2, new User {FirstName = "Name3"}),
new KeyValuePair<int, User>(2, new User {FirstName = "Name4"})
};
}
}
public class User
{
public string FirstName { get; set; }
}
Above as you can see there are multiple users for same key . Now I want to group them and convert the list object to dictionary in which the Key will be the same(1,2 as shown above) but the value will be the collection.Like this:
var outputNeed = new Dictionary<int, Collection<User>>();
//Output:
//1,Collection<User>
//2,Collection<User>
i.e they are grouped now.
How can I achieve that ?
I would suggest you use a
Lookup<TKey, TElement>instead. This data-structure is specifically intended for use as a map from keys to collections of values.Of course, if you do need the dictionary (to allow for mutability perhaps), you can do something like:
On another note, the
Collection<T>class is not all that useful unless you intend to subclass it. Are you sure you don’t just need aList<User>?