我有一个方法如下。它返回 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/