c# - 如何按 List<int> 对 List<Type> 进行排序?

标签 c# asp.net-mvc

在我的 C# MVC 项目中,我有一个项目列表,我想按另一个列表的顺序排序

var FruitTypes = new List<Fruit> {
    new Fruit { Id = 1, Name = "Banana"},
    new Fruit { Id = 2, Name = "Apple" },
    new Fruit { Id = 3, Name = "Orange" },
    new Fruit { Id = 4, Name = "Plum"},
    new Fruit { Id = 5, Name = "Pear" },
};

SortValues = new List<int> {5,4,3,1,2};

目前我的列表显示为默认的水果类型。

如何按 SortValues 对 Fruit 列表进行排序?

最佳答案

不清楚您是按 SortValues 中的索引排序,还是 SortValues 包含应连接的相应 Id 值。

第一种情况:

首先你必须Zip你的两个列表放在一起,然后你可以对 Zip 生成的复合类型进行排序,然后选择 FruitType 退出。

IEnumerable<FruitType> sortedFruitTypes = FruitTypes
    .Zip(SortValues, (ft, idx) => new {ft, idx})
    .OrderBy(x => x.idx)
    .Select(x => x.ft);

但是,这只是按照 SortValues 中指示的顺序对第一个列表进行排序,加入 ID。

在第二种情况下,一个简单的连接就足够了:

IEnumerable<FruitType> sortedFruitTypes =  SortValues
    .Join(FruitTypes, sv => sv, ft => ft.Id, (_, ft) => ft);

这是有效的,因为 Enumerable.Join 维护连接“左侧”的顺序。

关于c# - 如何按 List<int> 对 List<Type> 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49802853/

相关文章:

c# - RDotNet 数据帧查询

c# - 如何防止 ASP.NET MVC 中的某些 View 被缓存?

c# - 如何在 mvc4 razor 中显示验证消息

c# - CS0120 : An object reference is required for the nonstatic field, 方法或属性 'foo'

c# - 一系列存储过程(带有连续 token )是否比 Azure DocumentDb 中的单个普通查询慢?

c# - 如何使用类库中的 Controller ?

asp.net-mvc - 本地 IIS Web 服务器的 Git 推送式部署

asp.net - 使用 javascript、jquery 将 .ascx 页面呈现为 .aspx 页面

c# - 将 Blazor 支持添加到现有的 ASP .NET Core 2.1 MVC 应用程序

c# - 使用自定义控件在 silverlight 中设置样式与内联属性