【发布时间】:2012-11-20 20:45:01
【问题描述】:
我有一堂课Product:
class Product
{
int Id { get; set; }
string Name { get; set; }
int CategoryId { get; set; }
int PlantId { get; set; }
DateTime ProductionDate { get; set; }
}
我想在多个属性上使用LINQ GroupBy,但我事先不知道有多少以及哪些属性。例如,我可能只想按CategoryId、PlantId 或两者进行分组。我在网上找到了一篇描述如何use LINQ GrouBy dinamically的文章。
这确实可能很好用,但如果我想在不知道粒度的情况下在 ProductionDate.Year 和 ProductionDate.Month 上执行 Group By?作为粒度,我的意思是我是要对特定年份产生的所有Products 进行分组,还是将分组缩小到月份。
我找到的唯一合乎逻辑的解决方案是:
public ProductInfo GetGroupedProducts(int? year, int? month, int? selectedCategoryId, int? selectedPlantId)
{
List<Product> products = GetProducts();
var groupedProducts = products.GroupBy(p => new { (year == null ? p.ProductionDate.Year : string.Empty),
(month == null ? p.ProductionDate.Month : string.Empty),
(selectedCategoryId == null ? p.CategoryId : string.Empty),
(selectedPlantId == null ? p.PlantId : string.Empty)
});
//perform some additional filtering and assignments
}
但我想可能会有更清洁、更合适的解决方案。使用基于字符串的旧式查询构建方式,这项任务更容易完成。如果没有其他办法,我真的认为这是LINQ的一部分需要改进。
【问题讨论】:
-
好吧,我会使用
bool参数而不是int?... -
一个返回void的方法
GetGroupedProducts? -
@Rawling:我使用int?因为在 GroupBy 之后我还执行了一些过滤
-
@TimSchmelter:我可以更改返回类型,但我认为它与问题的上下文无关
-
由于您已经为每个可能要分组的字段传递了一个参数,因此您可以做任何非常动态的事情 - 或者更确切地说,需要 i> 做。 (与此相反,例如,如果您要传入字段名称的
string[],则需要使用反射或类似方法来获取正确的属性。)