I have some CartItems
which I have grouped by property FleetID
.
var groupedCartItems = cart.CartItems.OrderBy(x => x.FleetID)
.GroupBy(x => x.FleetID);
foreach (var fleetItem in groupedCartItems)
{
/////// var currentFleetID = fleetItem.GroupedFleetID; ////////
foreach(var itm in fleetItem)
{
}
}
In a loop of each group, how can I access the FleetID
property that it is grouped by?
Your case, you are grouping based on a single column, so it can be accessed through the group key. which means fleetItem.Key
will give you the key of the particular group in that iteration. if you want to access the same from inner loop means you can use itm.FleetID
.
foreach (var fleetItem in groupedCartItems)
{
var currentFleetID = fleetItem.Key; //outer loop
foreach(var itm in fleetItem)
{
var groupId = itm.FleetID; // inner loop
}
}
If you are performing the group based on more than one column means you can access them with respect to key, Consider that the grouping is like the folling:
var groupedCartItems = cart.CartItems.OrderBy(x => x.FleetID)
.GroupBy(x => new { x.FleetID,x.FleetName});
Then you can access them like the following:
foreach (var fleetItem in groupedCartItems)
{
var currentFleetID = fleetItem.Key.FleetID;
var currentFleetName = fleetItem.Key.FleetName;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With