Reputation: 463
I have similar request like in below link
"Grouping" dictionary by value
But I want to group based on property of the class.
public class myClass1
{
public int id { get; set; }
public string networkId { get; set; }
}
In below example I want a group of networkId
var obj1 = new myClass1() { id = 11, networkId = "asdf1" };
var obj2 = new myClass1() { id = 22, networkId = "asdf2" };
var obj3 = new myClass1() { id = 33, networkId = "asdf3" };
var obj4 = new myClass1() { id = 44, networkId = "asdf1" };
var obj5 = new myClass1() { id = 55, networkId = "asdf2" };
var obj6 = new myClass1() { id = 66, networkId = "asdf1" };
var obj7 = new myClass1() { id = 77, networkId = "asdf1" };
var classDictionary = new Dictionary<int, myClass1>();
classDictionary.Add(1, obj1);
classDictionary.Add(2, obj2);
classDictionary.Add(3, obj3);
classDictionary.Add(4, obj4);
classDictionary.Add(5, obj5);
classDictionary.Add(6, obj6);
classDictionary.Add(7, obj7);
Dictionary<myClass1, List<int>> test2 =
classDictionary.GroupBy(r => r.Value.networkId)
//.ToDictionary(t => t.Key, t => t.Select(r => r.Value).ToList());
So that the result would be like, a dictionary with key value as per below
"asdf1" -> List of obj1, obj4, obj6, obj7
"asdf2" -> List of obj2, obj5
"asdf3" -> List of obj3
Any help?
Upvotes: 1
Views: 1209
Reputation: 33823
You were very close. You simply need to update the target dictionary structure to the following:
Dictionary<string, List<myClass1>> test2 = classDictionary
.GroupBy(r => r.Value.networkId)
.ToDictionary(t => t.Key, t => t.Select(r => r.Value).ToList());
This creates the following output:
It is worth noting that this is an excellent use case for var
instead of explicitly naming the type, since it will determine your output type for you. This is often helpful when trying to determine what the end type will be.
Upvotes: 3