c# - 如何按另一个列表的顺序对列表进行排序?

标签 c# linq list

我有一个方法如下。它返回 MyTypes 的列表这似乎是由 myType.Id 订购的默认升序。我希望此列表按 ids 排序我传递给方法的参数。

public List<MyType> GetMyTypes(List<int> ids)
{
return (from myType in db.MyTypes
        where ids.Contains(myType.Id)
        select new MyType
        {
            MyValue = myType.MyValue
        }).ToList();
}

所以如果ids包含

302
300
301

返回的列表包含按升序排列的项目。

我需要做什么才能返回 List<MyType>按照ids的顺序?

谢谢

编辑:我试过orderby ids.IndexOf(myType.Id)但它抛出异常 Method 'Int32 IndexOf(Int32)' has no supported translation to SQL.

最佳答案

编辑:既然我在理解需求时所犯的错误已被指出,我建议将此作为实现预期结果的更高效的方法:

    public static List<MyType> GetMyTypes(List<int> ids)
    {
        int index = 0;
        Dictionary<int, int> positions = ids.ToDictionary(c => c, c => index++);
        MyType[] results = new MyType[ids.Count];

        foreach (MyType aType in (from myType in db.MyTypes
                                  where ids.Contains(myType.Id)
                                  orderby myType.Id
                                  select myType))
        {
            results[positions[aType.Id]] = aType;
        }

        return results.ToList();
    }

这不会通过 ids 列表搜索 db.MyTypes 中的每个元素(这是一件好事:它会很快!)。

我原来的(不正确的)答案:

使用 orderby 子句。

public List<MyType> GetMyTypes(List<int> ids) 
{ 
return (from myType in db.MyTypes 
        where ids.Contains(myType.Id) 
        orderby myType.Id
        select new MyType 
        { 
            MyValue = myType.MyValue 
        }).ToList(); 
} 

不清楚 db.MyTypes 返回什么类型的对象,但据推测,可以通过避免更新更多 MyType 对象来稍微简化代码。

public List<MyType> GetMyTypes(List<int> ids) 
{ 
return (from myType in db.MyTypes 
        where ids.Contains(myType.Id) 
        orderby myType.Id
        select myType).ToList(); 
} 

关于c# - 如何按另一个列表的顺序对列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2736024/

相关文章:

c# - 从本地数据库中选择数据

C#:如何在检查相等性时评估一个对象的多个计算机类?

c# - 使用 LINQ 获取数组中前 1000 个最大条目的数组索引值

c# - Int 和 Int 的 FirstOrDefault 行为?

c# - 在 ToDictionary 之前执行 ToList() 是否更好?

java - 列表未打印出其中一个变量

python - 如何将字典/列表存储在数据库中?

c# - 在数据库中存储连接字符串

python - 如何使用字典中的值替换列表中的部分值?

c# - 在 C# 中使用 CSV 作为 datagridview 的数据源