Entity Framework - Conditionally adding columns into group by

北慕城南 提交于 2020-01-11 10:44:11

问题


I want to conditionally add columns into GroupBy clause but I am not sure how it can be done.

I have 5 columns which I want to add in group by statement depending upon user's input. To do this I have following properties:

ProductId
ColorId
PieceId
SizeId
WeightId

If any property has value greater than 0 then this column needs to be used in group by clause.

So if ProductId, ColorId and PieceId has value greater than 0 than following should be there in group by:

list.GroupBy(p => new { p.Product.Id, p.ColorId, p.PieceId });

回答1:


Try something like that;

var groupedList = list.GroupBy(p => new
{
    ProductId = p.Product.Id > 5 ? p.Product.Id : (int?)null,
    ColorId = p.ColorId > 5 ? p.ColorId : (int?)null,
    PieceId = p.PieceId > 5 ? p.PieceId : (int?)null
})
.Select(x =>
new
{
    x.Key.ProductId,
    x.Key.ColorId,
    x.Key.PieceId
}).ToList();


来源:https://stackoverflow.com/questions/47827690/entity-framework-conditionally-adding-columns-into-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!