Link to home
Start Free TrialLog in
Avatar of Jobbietronic
JobbietronicFlag for United States of America

asked on

Dynamic Group By in Linq

Background: I have a class 'car', which amongst other things, has 2 properties which are, the number of doors and the number of seats. If I then create and enumerable List<car> of cars I want to group cars based on a selection made by the user. The user's selection will post back a string that I use in switch statement.
Is it possible to dynamically add a group by parameter to a Linq statement based on the user's selection or would I need to have a distinct Linq statement for each possible selection the user makes?
There could be any number of group by's and I don't want to repeat loads of code when the logic is identical each time, only the group by parameter changes.

The code I've stuck in below is an example; in reality the 'MORE STUFF TO DO' part is pretty long-winded which is why I don't want to repeat it for each case in the switch statement. I've seen something on ScottGu's blog about a framework but it seemed a bit much for what I needed.

Thanks,
J
///Non Dynamic Way
switch(sFilterProperty.ToLower())
{
case "number of seats":
var V1 = (from r in myList group r by (r.NmbSeats));
///MORE STUFF TO DO
break;
 
case "number of doors":
var V1 = (from r in myList group r by (r.NmbDoors));
///MORE STUFF TO DO
break;
 
default:
break;
}
 
//I'D LIKE SOMETHING LIKE 
{
     var property = ?????
    switch(sFilterProperty.ToLower())
     {
       case "number of seats":
       property = car.NmbSeats;
        break;
 
       case "number of doors":
       property =car.NmbDoors;
       break;
 
default:
break;
}
 
var MyGrouped List = (from r in myList group r by r.$property$);
///MORE STUFF TO DO
 
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial