复杂的orderby链接到另一个表

时间:2010-12-14 14:18:34

标签: linq linq-to-sql linq-to-entities linq-to-objects

我有以下查询开头:

var query = from p in db.Products
                        from pc in p.NpProductCategories
                        where pc.CategoryId == categoryId 
                        select p;

我正在对它应用更多过滤,最后我想对结果进行排序:

if (orderBy == ProductSortingEnum.Name)
                    query = query.OrderBy(x => x.Name);
                else
                    query = query.OrderBy(............);

我的大问题(来自不知道linq太好)来自ELSE。如何按不在当前结果集中的列对结果进行排序?我想以某种方式链接到orderby中的另一个linq查询。 我想要实现的排序是使用ProductId链接到NpProductVariants查询以匹配NpProductVariant和Products  并按NpProductVariant的价格

排序

2 个答案:

答案 0 :(得分:8)

假设您已在dbml ...

中设置了关系

一对一(以及多对一):

query = query.OrderBy(p => p.NpProductVariant.Price);

一对多:

query = query.OrderBy(p => p.NpProductVariants.Select(v => v.Price).Max());

此外:

var query =
  from p in db.Products 
  where p.NpProductCategories.Any(pc => pc.CategoryId == categoryId)
  select p;

答案 1 :(得分:1)

我认为您可以将Join挂钩到您的查询,只要它返回相同的内容即可。所以也许是这样的事情(我没有100%肯定,因为我还没有尝试过):

            query = from i1 in query
                 join i2 in query2 on i1.PropertyToJoin equals i2.PropertyToJoin
                 orderby i1.OrderProp1, i2.OrderProp2
                 select i1;

但我认为检查生成的sql以保持有效可能是个好主意。