English 中文(简体)
复杂秩序
原标题:complex orderby that links to another table

I have the following query to start with:

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

I m 对其应用一些更多的过滤器,最后,我想对结果进行分类:

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

My big problem (coming from not knowing linq too good) is the ELSE here. How can I sort results by a column that is not in the current result set? I would like to somehow link to another linq query in the orderby. The sorting I m trying to achive is to link to NpProductVariants query using the ProductId to match between NpProductVariant and Products and sort by the Price of the NpProductVariant

最佳回答

Assuming you have the relationship set up in the dbml...

一至一(及多至一):

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

For one to many:

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;
问题回答

I think you can hook your Join to your query as long as it is returning the same thing. So maybe something like (I m not 100 % sure since I haven t tried it):

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

但是,我认为,检查所生成的钢.可能是一个好的想法,因此它依然有效。





相关问题
LINQ to SQL and a running total on ordered results

I want to display a customer s accounting history in a DataGridView and I want to have a column that displays the running total for their balance. The old way I did this was by getting the data, ...

Can I do this with an IQueryable<T>?

is it possible to add an extension method to IQueryable<T> and then, for my Linq2Sql or EF or NHibernate or LinqToObjects, define it s functionality / how each repository will impliment this ...

AlphaNumeric ordering in SQL vs. LINQ and .NET

I encountered an interesting thing today that I have never noticed before. It appears that SQL and LINQ order AlphaNumeric strings differently. Data table contains rows: A G 6 P 1 D J 2 T Z 9 F 0 ...

If statement or Where extension with a For Each loop?

I was wondering which of the two code samples would be more efficient (or is the difference between the two negligible)? For Each apple in AppleController.GetRedApples().Where(Function(a) ...

Differences between LINQ to Objects and LINQ to SQL queries

I have been using LINQ to query my POCO objects for some time, but I have not yet tried LINQ to SQL. I assume that LINQ to SQL queries are somehow converted to equivalent SQL queries and, given this, ...

动态准则 询问

能否在业余时间建立LinqQuries。

热门标签