Get Grouped property in Loop with Linq C #
I have CartItems
one 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 the loop of each group, how can I access the property FleetID
it is grouped with?
source to share
In your case, you are grouping by one column, so it can be accessed using the group key. This means it fleetItem.Key
will give you the key of a specific group in this iteration. if you want to access it from the inner loop, then 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 running a group based on more than one column, that means you can access them by key, please note that the grouping is similar to the following:
var groupedCartItems = cart.CartItems.OrderBy(x => x.FleetID)
.GroupBy(x => new { x.FleetID,x.FleetName});
Then you can access them like below:
foreach (var fleetItem in groupedCartItems)
{
var currentFleetID = fleetItem.Key.FleetID;
var currentFleetName = fleetItem.Key.FleetName;
}
source to share
When you use GroupBy
, you end up with a collection of objects IGrouping
, each with the property Key
you want and can also be iterated over with a loop foreach
to get the items into a group. https://msdn.microsoft.com/en-us/library/bb343251(v=vs.110).aspx
var groupedCartItems = cart.CartItems.OrderBy(x => x.FleetID)
.GroupBy(x => x.FleetID);
foreach (var group in groupedCartItems)
{
var currentFleetID = group.Key; ////////
foreach(var itm in group)
{
}
}
source to share