LINQ 按空列排序,其中顺序为升序且空值应在最后 [英] LINQ order by null column where order is ascending and nulls should be last

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

问题描述

我正在尝试按价格对产品列表进行排序.

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

结果集需要按LowestPrice列的价格从低到高列出产品.但是,此列可以为空.

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

推荐答案

尝试将两列放在相同的 orderby 中.

Try putting both columns in the same orderby.

orderby p.LowestPrice.HasValue descending, p.LowestPrice

否则,每个 orderby 都是对每次重新排序的集合的单独操作.

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

这应该先对有值的进行排序,然后是值的顺序.

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

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

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