ascending/descending in LINQ - can one change the order via parameter?

后端 未结 4 892
时光取名叫无心
时光取名叫无心 2020-11-28 04:45

I have a method which is given the parameter \"bool sortAscending\". Now I want to use LINQ to create sorted list depending on this parameter. I got then this:



        
4条回答
  •  爱一瞬间的悲伤
    2020-11-28 04:57

    In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...

    var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()
    
    if(sortAscending) {
        qry = qry.OrderBy(x=>x.Property);
    } else {
        qry = qry.OrderByDescending(x=>x.Property);
    }
    

    Any use? You can create the entire "order" dynamically, but it is more involved...

    Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.

提交回复
热议问题