c# - 按另一个内存列表对内存列表进行排序

标签 c# asp.net linq linq-to-sql

是否可以通过另一个列表对内存列表进行排序(第二个列表将是引用数据源或类似的东西)?

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/

相关文章:

c# - 新窗口中的 Http 响应对象

c# - 无法在 C# 中解析 Oracle 时间戳

c# - DirectoryServices UserPrincipal.SetPassword 忽略密码策略(密码历史)

c# - 如何知道是否应用了 OrderBy 进行查询?

c# - 使用 LINQ 以在 C# 中通过匹配的子列表值选择列表

c# - Asp 图像按钮图像未更改

c# - 如何在不为每种情况使用 if 和 switch 语句的情况下重构链中的数百个条件?

c# - 仅在使用 LINQ 时引用需要错误

c# - 如何更新唯一的子 GridView?

c# - 如何更改 .Net 中整个进程(而不仅仅是当前线程)的 CurrentCulture?