我有两个表:
User {
PK: UserId
...
}
Product {
PK: ProductId,
FK: UserId
...
}
我有一个随机格式的 ProductId
列表。我不想对输出结果进行排序,我想为每个产品 ID 也包含用户数据。
以下代码以排序格式提供数据。我怎样才能避免这种排序?我希望对象列表与我们的产品列表的顺序相同。
List<Tables.Product> tblProductList =
repo.Products
.Include("User")
.Where(x => productIdList.Contains(x.ProductId))
.ToList();
最佳答案
I want the list of objects to be in the same order as our product list.
我假设我们的产品列表是指用于过滤的 productIdList
变量。
您不能在 LINQ to Entities 中执行此操作,因此您必须切换到 LINQ to Objects 并在内存中执行排序。
一种方法是使用 IndexOf
方法:
var tblProductList =
repo.Products
.Include("User")
.Where(x => productIdList.Contains(x.ProductId))
.AsEnumerable() // Switch to LINQ to Objects context
.OrderBy(x => productIdList.IndexOf(x.ProductId))
.ToList();
另一个更高效的方法(当 productIdList
很大时)可能是使用中间字典:
var productsById =
repo.Products
.Include("User")
.Where(x => productIdList.Contains(x.ProductId))
.ToDictionary(x => x.ProductId);
var tblProductList = productIdList
.Select(productId => productsById[productId])
.ToList();
关于c# - 如何根据 ID 列表对 EF 返回的对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37962057/