gpt4 book ai didi

c# - 如何根据 ID 列表对 EF 返回的对象进行排序?

转载 作者:太空狗 更新时间:2023-10-29 23:37:14 26 4
gpt4 key购买 nike

我有两个表:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com