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!