按分组属性值操作列表

时间:2016-10-19 07:13:46

标签: c# linq list

我有一个具有以下结构的类:

class Test 
{    
    int Value { get; set; }
    List<string> Categories { get; set }
}

我想对按标签分组的集合进行操作,例如:

List<Test> myData = new List<Test>{ add n items };

myData.GroupBy(x => x.Categories ).Count(); // I know this wont work

我想要实现的是能够在与谓词匹配的集合上执行操作,然后返回该集合的值。理想情况下,我希望有一个容器类:

class Metrics 
{    
    int Max { get; set; }
    int Min { get; set; }
    double Avg { get; set; }
    double Mode { get; set; }
}

然后像这样使用它(半伪代码)

Dictionary<string, Metrics> result = new Dictionary<string, Metrics>();

// find all unique categories across all my items in the list and then
foreach(string category in myData.Categories)
{    
   if(Tag not exists in result)
   {
       results.Add(category, new Metrics
       {
            Max = myData.GroupBy(x => x.Categories == category).Max,
            Avg = myData.GroupBy(x => x.Categories == category).Average()
       }); 
   }
}

1 个答案:

答案 0 :(得分:3)

SelectMany用于展平的匿名对象集合:

myData.SelectMany(item => item.Categories.Select(category => new { Category = category, Item = item}))
      .GroupBy(x => x.Category)
      .Where(/* The predicates you want to do */

由于您之后的查询似乎是每个代码数量的汇总,您还可以在Select之后添加另一个GroupBy,以便以后的聚合更简单:

.Select(grouping => new 
{ 
    Tag = grouping.Key,
    Amount = grouping.Count(),
    Items = grouping.Select(item => item.Item)
})