我有一个列表,目前正在使用.OrderBy
进行手动排序:
var newList = pouchList
.OrderBy(x => x.ID3Val)
.ThenBy(x => x.ID4Val == "LATE")
.ThenBy(x => x.ID4Val == "BED")
.ThenBy(x => x.ID4Val == "TEA")
.ThenBy(x => x.ID4Val == "LNCH")
.ThenBy(x => x.ID4Val == "MORN")
.ToList();
我想做的是在数组中具有将列表排序的参数,即:
[ "LATE", "BED", "TEA", "LNCH", "MORN" ]
以便我可以更改数组并使用这些参数对列表进行动态排序。
有人知道这是否可能吗?
答案 0 :(得分:0)
每次.OrderBy()
和.ThenBy()
调用都会返回一个IOrderedEnumerable
对象。您可以将OrderBy()
的结果存储在变量中,然后遍历值数组,并用每次ThenBy()
调用的结果替换该变量。像这样:
var orderingList = new string[] {"LATE", "BED", "TEA", "LNCH", "MORN"};
var newEnumerable = pouchList.OrderBy(x => x.ID3Val);
for(int i = 0; i < orderingList.Length; i++)
{
newList = newList.ThenBy(x => x.ID4Val == orderingList[i]);
}
var newList = newEnumerable.ToList();
这里有一个MSDN页面供参考:ThenBy