1

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?

Community
  • 1
  • 1
user3663854
  • 463
  • 2
  • 8
  • 21
  • 1
    Does this not work? `.ToDictionary(t => t.Key, t => t.Select(r => r.Value).ToList());` – Rob May 19 '16 at 02:07
  • Nope, some compilation error – user3663854 May 19 '16 at 02:10
  • 1
    Oh, it should be `var test2 = ` (or `Dictionary> test2 =`), since you want a list of `myClass1`, not `int`. Also, in the future, please include error messages, not just that it's a compilation error - that doesn't help very much :) – Rob May 19 '16 at 02:10
  • yeah, I should include it from the start. Looking at answer below, if I just make it to var test2 like you mentioned, this question wont pop up. Thanks for the help! I should just do that from the beginning... – user3663854 May 19 '16 at 02:17

1 Answers1

3

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:

enter image description here

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.

David L
  • 32,885
  • 8
  • 62
  • 93