我有一个与列标题一起显示的数据表。单击标题时,它将使用Linq根据该列对数据集进行排序:
datatable.OrderByDescending(x => x.ColumnHeader).ToList()
目前,我有一种方法,可以将标头名称传递给切换用例,然后将其吐出格式正确的Linq语句
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;
}
但这是很多重复的代码。我想知道是否有一种方法可以完成以下任务:
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...
}
或者,如果有办法更好地完成我想做的事情,请告诉我!