0

I have many date in one variable like:

var date = hfAllDates.Value.Split('#');

there are four date(01/01/2016,22/01/2016,18/01/2016,05/01/2016) in date variable .

how to sort date.

Thanks

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • I don't understand your question. What is the `hfAllDates` exactly? You are not sorting anything, you are splitting something but that's not clear as well. – Soner Gönül Jan 22 '16 at 07:11
  • did you tried anything? – Arijit Mukherjee Jan 22 '16 at 07:11
  • is the type of date `string[]`? Then you may need to convert each element to `DateTime` first. Then you can sort it easily. – Ian Jan 22 '16 at 07:11
  • 6
    This isn't quite a duplicate of [this question](http://stackoverflow.com/questions/14667754/sort-string-list-with-dates-in-c-sharp), since that one deals with lists rather than arrays. However, considering how easy it is to convert an array to a list, the answer on that question still applies. – Elezar Jan 22 '16 at 07:16

4 Answers4

3

add namespace using System.Linq;

and use LINQ Query

in ascending order

  var orderedDateList = date.OrderBy(x => DateTime.Parse(x)).ToList();

in Descending oreder

var orderedDateList = date.OrderByDescending(x => DateTime.Parse(x)).ToList();
2

Convert date from string[] to List<DateTime> first:

List<DateTime> dtList = date.Select(x => DateTime.Parse(x)).ToList();

Then you can easily sort it:

dtList.Sort();
Ian
  • 30,182
  • 19
  • 69
  • 107
1

Using Linq's OrderBy:

var sortedDates = date.OrderBy(x => DateTime.Parse(x));

or

var sortedDates = date.OrderByDescending(x => DateTime.Parse(x));

if you are needed to sort dates descending

Mikhail Tulubaev
  • 4,141
  • 19
  • 31
1

I suggest using Linq:

var date = hfAllDates.Value.Split('#')
  .Select(line => DateTime.Parse(x))
  .OrderBy(x => x)
  .ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215