1

To elaborate on what I'm asking here, I'm working in C# trying to order a list of data that is coming out of a database. A certain object (table) has two separate properties (columns) which can hold dates. I want to sort this list based on date, meaning for each data row, I want to take the maximum of the two dates and use that for the sort.

Is there an elegant way to do this? At the moment I'm thinking that I should just get the max time from each record, and store it as a key in a Dictionary, with the data row being the value, and then iterate through the Dictionary with the sorted keys. Although this wouldn't be terrible to code, I'm trying to see if there is a nicer way to do this using Linq. Any help would be appreciated. Thanks.

user535617
  • 634
  • 2
  • 7
  • 22

1 Answers1

1

If you want an alternative for sorting your collection everytime, .NET contains a class called SortedList. Here is the link to the MSDN article: http://msdn.microsoft.com/en-us/library/system.collections.sortedlist(v=vs.110).aspx

MSDN states that a SortedList:

Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.

So if you want to sort by date you can declare your sorted list as:

SortedList<DateTime, YourData> mySortedList = new SortedList<DateTime, YourData>();

and when you add values to it, it will already be sorted. Or you can just go with LINQ and @Alexander answer.

Edit

I just understood what you want to do. You can do:

table.OrderBy(item => Math.Max(item.Date1.Ticks, item.Date2.Ticks));

Note: The linq query above will not be performant on a large collection.

The Mahahaj
  • 696
  • 6
  • 8