Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Grouped Property in Loop with Linq C#

Tags:

c#

linq

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?

like image 613
Brendan Gooden Avatar asked Oct 17 '25 22:10

Brendan Gooden


1 Answers

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;   
}
like image 162
sujith karivelil Avatar answered Oct 20 '25 11:10

sujith karivelil