【问题标题】:Linq "group by" values in a Dictionary property with a list of keys带有键列表的 Dictionary 属性中的 Linq“分组依据”值
【发布时间】:2012-02-24 19:21:39
【问题描述】:

我有以下对象列表

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”

但实际上我需要做的是按“attA”和“attC”(或 groupBy 变量中的任何内容)分组并获得以下四个组:

  • “1_1”-“o1 o2”
  • “1_2”-“o3 o4”
  • “2_3”-“o4 o5”
  • “2_4”-“o7 o8”

【问题讨论】:

    标签: linq dictionary group-by


    【解决方案1】:
    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 键列表中获得的字典值的串联投影。

    【讨论】:

    • 工作如梦。如果您曾经访问过索非亚,请知道您从我这里获得了免费啤酒。
    • @AdrianIftode,您使用扩展方法的查询相当于什么?喜欢var query=source.GroupBy(....
    【解决方案2】:

    您可以按多个属性分组:

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

    【讨论】:

    • 是的,工作正常,但我需要按属性分组,包含在 'List groupBy' 变量中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多