可以通过另一个列表对内存列表进行排序(第二个列表将是参考数据源或类似的东西)?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#读取XML多级子节点 2022-11-05
- C#中类与接口的区别讲解 2023-06-04
- C#通过GET/POST方式发送Http请求 2023-04-28
- C# Winform实现石头剪刀布游戏 2023-01-11
- C# – NetUseAdd来自Windows Server 2008和IIS7上的NetApi32.dll 2023-09-20
- Unity shader实现多光源漫反射以及阴影 2023-03-04
- 使用c#从分隔文本文件中插入SQL Server表中的批量数据 2023-11-24
- C#集合查询Linq在项目中使用详解 2023-06-09
- c#中利用Tu Share获取股票交易信息 2023-03-03
- 京东联盟C#接口测试示例分享 2022-12-02