c# - 使用数组对 List<T> 进行排序

标签 c# arrays linq list sorting

基本上我有一个包含所有项目的列表。然后我有一个字符串,其中包含我想要从列表中获取的 ID,为此,我将字符串拆分为 Int 数组,然后使用它和 LINQ 从列表中获取我想要的项目

像这样:

List<T> lstAllList = Model.getAllItems();

string stringIDs = "8,9,12,11,7";

int[] intArray = stringIDs.Split(',').Select(n => Convert.ToInt32(n)).ToArray();

List<T> lstLimitedList = (from r in lstAllList where intArray.Contains(r.id) select r).ToList();

效果很好。

但这里的问题是我希望我的列表以与 ID 字符串相同的方式排序,即 8,9,12,11,7,如本例所示。 但是LINQ返回的列表默认是按照id排序的,所以返回的列表是7,8,9,11,12。

有没有办法阻止它像这样排序,或者有没有办法用我的 int 数组对新列表进行排序?

最佳答案

当然,只需按数组中 ID 的索引排序即可:

string stringIDs = "8,9,12,11,7";

int[] intArray = stringIDs.Split(',').Select(n => Convert.ToInt32(n)).ToArray();

var lstLimitedList = (
        from r in lstAllList 
        where intArray.Contains(r.id) 
        orderby Array.IndexOf(intArray, r.id)   // <--------
        select r).ToList();

关于c# - 使用数组对 List<T> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23365091/

相关文章:

ios - Swift 中具有固定返回类型的子类 objc 数组中需要进行强制转换

javascript - 'array[i]=undefined' 是否生成稀疏数组?

asp.net-mvc - LinqToDB : How to change connection string, 或在不使用项目配置的情况下设置它

c# - 单击事件的 GridView 列标题

c# - 为什么不能转换此double值

arrays - 最佳引用二维数组?

c# - 使用 WCF 数据服务时出错

c# - LINQ Group By 多列并进行计数

c# - 秒表记录至小数点后 4 位

c# - 使用 .NET 与 MS Excel 进行 COM 互操作的(免费)替代方案是什么(如果有的话)?