C# 如何根据ID列表对EF返回的对象进行排序?
我有两张桌子:C# 如何根据ID列表对EF返回的对象进行排序?,c#,entity-framework,asp.net-web-api,C#,Entity Framework,Asp.net Web Api,我有两张桌子: User { PK: UserId ... } Product { PK: ProductId, FK: UserId ... } 我有一个随机格式的ProductIds列表。我不想对输出结果进行排序,我想包括每个产品Id的用户数据 下面的代码以排序格式提供数据。如何避免这种排序?我希望对象列表的顺序与产品列表的顺序相同 List<Tables.Product> tblProductList = repo.Prod
User {
PK: UserId
...
}
Product {
PK: ProductId,
FK: UserId
...
}
我有一个随机格式的ProductId
s列表。我不想对输出结果进行排序,我想包括每个产品Id的用户数据
下面的代码以排序格式提供数据。如何避免这种排序?我希望对象列表的顺序与产品列表的顺序相同
List<Tables.Product> tblProductList =
repo.Products
.Include("User")
.Where(x => productIdList.Contains(x.ProductId))
.ToList();
List-tblProductList=
回购产品
.包括(“用户”)
.Where(x=>productIdList.Contains(x.ProductId))
.ToList();
我希望对象列表的顺序与产品列表的顺序相同
List<Tables.Product> tblProductList =
repo.Products
.Include("User")
.Where(x => productIdList.Contains(x.ProductId))
.ToList();
我假设我们的产品列表是指用于筛选的productIdList
变量
在LINQtoEntities中不能这样做,因此必须切换到LINQtoObjects,并在内存中进行排序
一种方法是使用以下方法:
另一种更有效的方法(当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();
没有默认排序。除非指定OrderBy子句,否则数据库将返回对象而不进行排序。由于某些操作(如Distinct)使用Sort,它们可能看起来是有序的。即使是这些查询也将是无序的,但如果查询的开销足以并行化,那么什么是
productIdList
?从另一个表或一个ID列表加载的东西?productIdList包含整数ID列表。但它来自哪里?如果它来自一个表,您也可以包括另一个表,并按表上的某些字段排序。如果只是一个ID列表,那么必须在客户端对结果重新排序。在SQL中,无法根据任意ID列表对查询结果重新排序。在客户端,您可以创建(ProductID,Order)
对的列表,将其与ProductID和Order上的结果通过Order
列进行联接。ORMs使用关系,而不是联接。当关系已经定义时,绝对没有理由使用join
。事实上,使用连接而不是像往常一样映射关系是一个错误:)对于10个productIdList,上面的查询需要10秒钟。有什么方法可以改进它吗?原始查询需要多长时间?原始查询需要2到3秒,但有时此查询也需要4到5秒,但通常需要10秒左右。嗯,在内存中排序10条记录不会给原始查询增加超过几毫秒的时间。在测量原始查询时,包括ToList()
call,对吗?
var productsById =
repo.Products
.Include("User")
.Where(x => productIdList.Contains(x.ProductId))
.ToDictionary(x => x.ProductId);
var tblProductList = productIdList
.Select(productId => productsById[productId])
.ToList();