Sorting a collection by multiple fields

后端 未结 4 733
甜味超标
甜味超标 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 07:54

    I would create a class to hold your information

    public class NameDate
    {
        private string name;
        private DateTime date;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public DateTime Date
        {
            get { return date; }
            set { date = value; }
        }
    }
    

    I would then populate a List<NameDate> to hold your items. When this is done, to sort the items you can use LINQ

    List<NameDate> someList = new List<NameDate>();
    someList = GetNameDateList();
    var orderedByNameList = someList.OrderBy(e => e.Name);
    var orderedByDateTimeList = someList.OrderBy(e => e.Date);
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-21 07:55

    You can use Linq function ThenBy after using OrderBy to perform further sorting.

    listOfRecords.OrderBy(p => p.Name).ThenBy(p => p.Date)
    
    0 讨论(0)
  • 2020-12-21 07:59

    Something like this:

    yourList.OrderBy(o => o.DateTime).ThenBy(o => o.Number);
    
    0 讨论(0)
  • 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<object>({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<object> 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.

    0 讨论(0)
提交回复
热议问题