LINQ为了通过空列,其中顺序是升序和空值应该是最后一次 [英] LINQ order by null column where order is ascending and nulls should be last

查看:1457
本文介绍了LINQ为了通过空列,其中顺序是升序和空值应该是最后一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过他们的价格来排序的产品列表。



结果集需要由列 LowestPrice 来列出了产品价格从低到高。然而,这列可以为空。



我可以像降序对列表进行排序这样:

 在_context.Products 
从对VAR的产品=其中p.ProductTypeId == 1
排序依据p.LowestPrice.HasValue降
排序依据p.LowestPrice降
器选择p;

//返回:102,101,100,NULL,NULL



但我无法弄清楚如何升序排列此

  //想我:100,101, 102,NULL,NULL 


解决方案

尝试把两列在同样的排序依据。

 排序依据p.LowestPrice.HasValue下降,p.LowestPrice 

否则,每个排序依据是集单独运行,每次重复订购吧。



这应该订购那些用一个价值第一,然后选择值的顺序。


I'm trying to sort a list of products by their price.

The result set needs to list products by price from low to high by the column LowestPrice. However, this column is nullable.

I can sort the list in descending order like so:

var products = from p in _context.Products
   where p.ProductTypeId == 1
   orderby p.LowestPrice.HasValue descending
   orderby p.LowestPrice descending
   select p;

// returns:    102, 101, 100, null, null

However I can't figure out how to sort this in ascending order.

// i'd like: 100, 101, 102, null, null

解决方案

Try putting both columns in the same orderby.

orderby p.LowestPrice.HasValue descending, p.LowestPrice

Otherwise each orderby is a separate operation on the collection re-ordering it each time.

This should order the ones with a with a value first, "then" the order of the value.

这篇关于LINQ为了通过空列,其中顺序是升序和空值应该是最后一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆