LInq排序依据和Desc排序 [英] LInq Order By and Order By Desc
问题描述
我正在使用"Linq"来过滤对象列表并对它们进行排序,例如
I am using "Linq" to filter list of objects and to sort them, like
myList.Where(x => x.Item!= "SF" && x.AdSize == minadSize)
.OrderBy(x => x.ManufacturingDate)
.OrderBy(x=>x.ExpiryDate);
我怀疑自己是否正确,那就是如果我想在多个字段上排序",那么是否有必要使用多个Order By子句,而不能通过单个"OrderBy"来完成
I doubt whether i am doing it right or not that is if i want to "sorting" on multiple fields then is it necessary to use multiple Order By clause cant it be done with single "OrderBy"
推荐答案
不要使用多个OrderBy
调用-使用OrderBy
后跟ThenBy
:
Don't use multiple OrderBy
calls - use OrderBy
followed by ThenBy
:
var query = myList.Where(x => x.Item!= "SF" && x.AdSize == minadSize)
.OrderBy(x => x.ManufacturingDate)
.ThenBy(x => x.ExpiryDate); // Could add more ThenBy calls
如果您两次使用OrderBy
,它将按到期日期对已按日期排序的列表进行重新排序,而我假设您只想按到期日期对具有以下内容的商品进行排序等于制造日期,即上述日期.
If you use OrderBy
twice, it will reorder the already-ordered-by-date list by expiry-date, whereas I assume you only want to order by expiry date for items with an equal manufacturing date, which is what the above does.
显然也有一个ThenByDescending
方法.例如:
Obviously there's a ThenByDescending
method too. For example:
var query = people.OrderBy(x => x.LastName)
.ThenBy(x => x.FirstName)
.ThenByDescending(x => x.Age)
.ThenBy(x => x.SocialSecurity);
这篇关于LInq排序依据和Desc排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!