2012-02-24 43 views
2

的列表我已经所以我需要对象LINQ的“组由”值时,键

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" } } }); 

的以下列表组它由特定的属性(一个或多个)的值,此外这些属性的名称都保存在一个单独的列表,如:

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

我尝试使用

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

这工作正常,返回2组:

  • “1” - “O1,O2 O3 O4”
  • “2” - “O5 O6 O7 O8”

,但究竟是什么,我需要做的是按“阿塔”和“美洲热带金枪鱼委员会”(或无论是在GROUPBY变量),并得到以下四组:

  • “1_1” - “O1,O2”
  • “1_2” - “ o3 o4“
  • “2_3” - “O4 O5”
  • “2_4” - “O7 O8”

回答

4
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() 
}; 

组密钥是级联字典值的投影groupBy键列表。

+0

像梦一样工作。如果你曾去过索非亚,知道你从我那里得到了一杯免费的啤酒。 – Sinnerman 2012-02-25 17:12:38

+0

我会喜欢的,谢谢,邻居! – 2012-02-25 17:18:30

+0

@AdrianIftode,你使用扩展方法的查询的等价物是什么?像'var query = source.GroupBy(....' – burhan 2014-03-09 09:32:49

0

您可以将多个属性:

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); 
+0

是的,工作正常,但我需要按属性列出,包含在'List groupBy'varialbe – Sinnerman 2012-02-24 19:36:04