Group by in Linq with condition

Viewed 58

I want to group by a table with Order Id but if one of price is negative don’t group by and brings all rows in output

I use below code but group by all order id

tblResult = tblResult.AsEnumerable().GroupBy(r => new { orderId = r["OrderID"] }).Select(g =>
                {
                    var row = tblResult.NewRow();
                    row["Order ID"] = g.Key.orderId;
                    row["Price"] = g.Sum(r => float.Parse(r.Field<string>("Price"))).ToString();
                    return row;
                }).CopyToDataTable();

enter image description here

1 Answers

You can create your condition in grouping, the tricky part is the result would be a list for those with negative prices and single item for those without it. if we also make single items as list then SelectMany() shoud do what you want:

var result = list.GroupBy(x => x.Id)
             .SelectMany(g => g.Any(x => x.Price < 0)?
                         g.ToList():
                         new List<Order> { new Order { Id = g.Key, Price = g.Sum(grp => grp.Price)}});

LIVE DEMO

Related