2016-06-22 63 views
5

我有两个表:如何根据ID列表对EF返回的对象进行排序?

User { 
    PK: UserId 
    ... 
} 

Product { 
    PK: ProductId, 
    FK: UserId 
    ... 
} 

我的ProductId S IN随机格式的明细表。我不想对输出结果进行排序,我也想为每个产品ID包含用户数据。

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

List<Tables.Product> tblProductList = 
    repo.Products 
     .Include("User") 
     .Where(x => productIdList.Contains(x.ProductId)) 
     .ToList(); 
+3

有默认没有这样的东西排序。除非您指定OrderBy子句,否则数据库将返回对象而不进行排序。他们*可能*显示有序,因为一些操作(例如Distinct)使用Sort。即使这些将是无序的,虽然如果查询是昂贵的并行化 –

+0

什么是'productIdList'?从另一个表加载的东西或只是一个ID列表? –

+0

productIdList包含Integer ID列表。 –

回答

2

我希望对象的名单在同一顺序我们的产品清单。

我想通过我们的产品清单你的意思是用于过滤的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(); 
+0

感谢一如既往:) –

+0

对于10个productIdList,上述查询需要10秒。有什么方法可以改进它吗? –

+0

原始查询需要多长时间? –

-1
var tblProductList=(from product in repo.Products 
        join user in repo.Users on product.UserId equals user.UserId 
        select new { Product=product,User=user}).toList(); 
+1

ORM使用关系,而不是联接。当关系已经定义时,绝对没有理由使用'join'。事实上,这是一个使用连接而不是映射关系的错误 –

相关问题