小编典典

LINQ 按空列排序,其中顺序为升序,空值应在最后

all

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

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

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

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

但是我不知道如何按升序对其进行排序。

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

阅读 50

收藏
2022-08-29

共1个答案

小编典典

尝试将两列放在同一个 orderby 中。

orderby p.LowestPrice.HasValue descending, p.LowestPrice

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

这应该首先对具有值的那些排序,然后是值的顺序。

2022-08-29