2012-02-24 40 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