Reputation: 31
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 });
Upvotes: 2
Views: 810
Reputation: 13146
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();
Upvotes: 2