Sinnerman
Sinnerman

Reputation: 23

Linq "group by" values in a Dictionary property with a list of keys

I have the following list of objects

List<Obj> source = new List<Obj>();
source.Add(new Obj() { Name = "o1", Attributes = new Dictionary<string, string> { { "attA", "1" }, { "attB", "1" }, { "attC", "1" } } });
source.Add(new Obj() { Name = "o2", Attributes = new Dictionary<string, string> { { "attA", "1" }, { "attB", "2" }, { "attC", "1" } } });
source.Add(new Obj() { Name = "o3", Attributes = new Dictionary<string, string> { { "attA", "1" }, { "attB", "3" }, { "attC", "2" } } });
source.Add(new Obj() { Name = "o4", Attributes = new Dictionary<string, string> { { "attA", "1" }, { "attB", "4" }, { "attC", "2" } } });
source.Add(new Obj() { Name = "o5", Attributes = new Dictionary<string, string> { { "attA", "2" }, { "attB", "5" }, { "attC", "3" } } });
source.Add(new Obj() { Name = "o6", Attributes = new Dictionary<string, string> { { "attA", "2" }, { "attB", "6" }, { "attC", "3" } } });
source.Add(new Obj() { Name = "o7", Attributes = new Dictionary<string, string> { { "attA", "2" }, { "attB", "7" }, { "attC", "4" } } });
source.Add(new Obj() { Name = "o8", Attributes = new Dictionary<string, string> { { "attA", "2" }, { "attB", "8" }, { "attC", "4" } } });

so i need to group it by the values of a specific attribute(s), furthermore the names of these attributes are kept in a separate list, like:

List<string> groupBy = new List<string>() { "attA", "attC" };

i tried using

var groups =
       from s in source
       group s by s.Attributes["attA"];

this works fine, returning 2 groups:

but what actually I need to do is to group by "attA" and "attC" (or whatever is in the groupBy variable) and get the following four groups:

Upvotes: 2

Views: 1963

Answers (2)

Adrian Iftode
Adrian Iftode

Reputation: 15663

from c in source
group c by String.Join("_",groupBy.Select(gr=>c.Attributes[gr]).ToArray()) into gr
select new 
{
   AttrValues = gr.Key,
   //Values = gr.Key.Split('_'),
   Names = gr.Select(c=>c.Name).ToList()
};

The group key is the concatenated projection of the dictionary values obtained from groupBy list of keys.

Upvotes: 4

BrokenGlass
BrokenGlass

Reputation: 160862

You can group by multiple properties:

var groups = from s in source
             group s by new 
             { 
                AttributeA = s.Attributes["attA"], 
                AttributeC = s.Attributes["attC"] 
             };

//shows 4 groups
foreach (var group in groups)
    Console.WriteLine(group.Key.AttributeA + "_" + group.Key.AttributeC);

Upvotes: 0

Related Questions