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

Jyo*_*ngh 5 c# entity-framework asp.net-web-api

我有两张桌子:

User {
    PK: UserId
    ...
}

Product {
    PK: ProductId, 
    FK: UserId
    ...
}
Run Code Online (Sandbox Code Playgroud)

我有一个ProductId随机格式的列表.我不想对输出结果进行排序,我想为每个产品ID包含用户数据.

以下代码以排序格式提供数据.我怎样才能避免这种排序?我希望对象列表与我们的产品列表的顺序相同.

List<Tables.Product> tblProductList =
    repo.Products
        .Include("User")
        .Where(x => productIdList.Contains(x.ProductId))
        .ToList(); 
Run Code Online (Sandbox Code Playgroud)

Iva*_*oev 6

我希望对象列表的顺序与我们的产品列表的顺序相同。

我假设我们的产品列表是指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();
Run Code Online (Sandbox Code Playgroud)

另一种性能更高的方法(当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();
Run Code Online (Sandbox Code Playgroud)