可以通过另一个列表对内存列表进行排序(第二个列表将是参考数据源或类似的东西)?public class DataItem{public string Name { get; set; }public string Path { get; set; }}// a list of Data Items, randomly s...

可以通过另一个列表对内存列表进行排序(第二个列表将是参考数据源或类似的东西)?
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# – 按内存列表中的另一个内存列表排序


基础教程推荐
猜你喜欢
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- Unity shader实现高斯模糊效果 2023-01-16
- C#中的Linq to JSON操作详解 2023-06-08
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C# 解析XML和反序列化的示例 2023-04-14
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- 实例详解C#实现http不同方法的请求 2022-12-26