Sorting a collection by multiple fields

后端 未结 4 726
甜味超标
甜味超标 2020-12-21 07:17

I need to sort a collection. For example, I have

Austin 12/3/2012   
Sam 100 12/3/2012   
Sam 200 14/3/2012   
Bubly 300 12/3/2012   
Bubly 300 15/3/2012  
         


        
4条回答
  •  情话喂你
    2020-12-21 08:06

    First you create two functions:

    var SortByDate=(p=>p.Date);
    var SortByName=(p=>p.Name);
    

    Then you have, for example, a List containing the two

    var SortDimensions=new List({SortByDate,SortByName});
    
    
    

    Then you if you want to sort by first date then name you do:

    myList.OrderBy(SortDimensions[0]).ThenBy(SortDimensions[1]);
    

    Now, here is the tricky part, if you want to sort by name first then date you just alter the order of the functions in the SortDimensionsList:

    SortDimensions.Remove(SortByName);
    SortDimensions.Insert(0,SortByName);
    

    This way, the same OrderBy statement will give you a different result.

    PS. Admittedly, this is rather close to being pseudocode since you may have to use something other than List for the SortDimensions collection to avoid compiler errors, but I don't have access to an IDE at the moment, but the spirit of the answer remains the same. Create a collection, store delegate functions in it, then alter the order within the collection to achieve different sorting dimensions using the same generic code.

    提交回复
    热议问题