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

标签 c# entity-framework asp.net-web-api

我有两个表:

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/

相关文章:

c# - EF Code First 中的静态构造函数的使用

c# - 当 Index.cshtml 页面明显存在时,Razor 引擎找不到该页面

.net - Asp.net Web API - 如何为自定义 CSV 媒体类型格式化程序设置文件名

c# - 对 Web Api 的 MVC 请求

c# - 在 WPF 中处理文本框上的 Enter 事件时,如何接受 Ctrl+Enter 作为返回?

c# - 使用反射时如何忽略属性

c# - EF,代码优先 - 如何在插入时设置自定义 Guid 标识值

c# - 禁用自动更改检测会在EF中引起哪些错误?

c# - 在 WPF 中显示错误消息文本框

c# - 在 asp.net 中比较日期和今天