将聚合动态应用于Linq IGrouping元素

时间:2015-05-28 22:04:26

标签: c# linq

我需要对Collection<Dictionary<string,object>>进行一些基本聚合。每次分组和聚合的字段都会更改,要应用的聚合函数也是如此。我能够对元素进行分组,现在我想知道如何应用用户选择的自定义聚合函数。

示例:

// Data I want to aggregate
Collection<Dictionary<string,object>> userData;
// The key is the field, and the value is the name of the aggregate function to apply. Ex: {"distance", "average"},{"time","sum"},{"price","customAgg"}
Dictionary<string,string> fieldsToAggregate; 

var groupedData = userData.GroupBy( /* here I selected all the fields that are not being aggregated */ )

foreach(var group in groupedData)
{
  // Here is where I don't know how to best handle it ...
}

我目前的做法是在switch()上执行fieldsToAggregate并调用它引用的函数(或者是现有的Linq聚合,如.Sum()或自定义在代码中的其他位置)。

case "sum":
   group.Sum(/* I select here the appropriate field */);
   break;

这太静态,其他应用程序/类无法扩展此功能。有一个更好的方法吗?也许.Aggregate()有代表?

0 个答案:

没有答案