可以通过另一个列表对内存列表进行排序(第二个列表将是参考数据源或类似的东西)?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# 模拟线性回归的示例 2023-03-14
- user32.dll 函数说明小结 2022-12-26
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- Unity3D实现渐变颜色效果 2023-01-16
- Unity Shader实现模糊效果 2023-04-27
- .NET CORE DI 依赖注入 2023-09-27
- 如何使用C# 捕获进程输出 2023-03-10
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- Oracle中for循环的使用方法 2023-07-04