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
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.
You can use Linq function ThenBy after using OrderBy to perform further sorting.
listOfRecords.OrderBy(p => p.Name).ThenBy(p => p.Date)
Something like this:
yourList.OrderBy(o => o.DateTime).ThenBy(o => o.Number);
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.