LInq Order By and Order By Desc

家住魔仙堡 提交于 2019-12-07 01:50:47

问题


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);

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"


回答1:


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

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.

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);


来源:https://stackoverflow.com/questions/6305700/linq-order-by-and-order-by-desc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!