是否可以通过另一个列表对内存列表进行排序(第二个列表将是引用数据源或类似的东西)?
public class DataItem
{
public string Name { get; set; }
public string Path { get; set; }
}
// a list of Data Items, randomly sorted
List<DataItem> dataItems = GetDataItems();
// the sort order data source with the paths in the correct order
IEnumerable<string> sortOrder = new List<string> {
"A",
"A.A1",
"A.A2",
"A.B1"
};
// is there a way to tell linq to sort the in-memory list of objects
// by the sortOrder "data source"
dataItems = dataItems.OrderBy(p => p.Path == sortOrder).ToList();
最佳答案
首先,让我们为 sortOrder
中的每个项目分配一个索引:
var sortOrderWithIndices = sortOrder.Select((x, i) => new { path = x, index = i });
接下来,我们加入两个列表并排序:
var dataItemsOrdered =
from d in dataItems
join x in sortOrderWithIndices on d.Path equals x.path //pull index by path
orderby x.index //order by index
select d;
这也是您在 SQL 中执行此操作的方式。
关于c# - 按另一个内存列表对内存列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24714026/