0

I have a datatable that is displayed with the column headers. When clicking the headers, it will sort the dataset based on that column by means of Linq:

datatable.OrderByDescending(x => x.ColumnHeader).ToList()

Currently, I have a method that passes in the header name to a switch case that will then spit out the properly formatted Linq statement

switch (fruitType)
{
    case "Apple":
    output = output.OrderByDescending(x => x.Apple).ToList();
    break;
case "Orange":
    output = output.OrderByDescending(x => x.Orange).ToList();
    break;
case "Peach":
    output = output.OrderByDescending(x => x.Peach).ToList();
    break;
case "Grapefruit":
    output = output.OrderByDescending(x => x.Grapefruit).ToList();
    break;
}

But this is a lot of repetitive code. I am wondering if there is a way to accomplish the following:

List<FruitBasket> output = GetFruitBasket();
List<string> fruitTypes = new List<string>(new string[] { "Apple",
                                                          "Orange", 
                                                          "Peach",
                                                          "Grapefruit" });
foreach (string type in fruitTypes)
{
    string query = $"output.OrderByDescending(o => o.{type}).ToList()";
    output = SomehowRunAsLinq(query);
    // Do stuff...
}

Alternatively, if there is a way to accomplish what I am trying to do in a better way, please let me know!

Guitrum
  • 171
  • 1
  • 10

1 Answers1

0

It would seem that Dynamic LINQ might be the answer you're looking for. I remember faintly that you can't transcode string to linq easily. It was quite a mission when I tried it.

Hope this puts you in the right direction

Gawie Schneider
  • 1,078
  • 1
  • 9
  • 14