virtualreality
virtualreality

Reputation: 15

Sort object array dates, where dates are of string data type c#

Trying to sort these datesw

object[] Dates = pivotGridFieldDates.GetUniqueValues();

result of Dates

9/10/2015
9/11/2015
9/2/2015
9/20/2015
9/25/2015
9/7/2015
9/8/2015

Dates format change as per the culture preference and I would like to sort these object array dates....

where Datetype of "Dates"  is {Name = "String" FullName = "System.String"}

My code

object[] Dates = pivotGridFieldDates.GetUniqueValues();
string result;

List<string> list=new List<string>();
var map = new List<String>();
foreach (var value in Dates)
{
    string map1= Convert.ToString(value);
    DateTime newdate = DateTime.ParseExact(map1, culture.ShortDatePattern,
                CultureInfo.InvariantCulture);
    result = newdate.ToString("yyyyMMdd");
    map.Add(result);
}
map.Sort();

After sorting, how can I convert this "map" list to object[] weeks dates again ?? and display dates in same date-format as it was before sorting...

Upvotes: 0

Views: 679

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

You can simply use OrderBy (or maybe OrderByDescending) to sort sequence. Also no need to separate list - just Select to perform conversion like:

var listOfSortedStringDates = Dates.Select(v => DateTime.ParseExact( // parse
       v.ToString(),  // ToString as we have objects
       culture.ShortDatePattern, CultureInfo.InvariantCulture))
   .OrderBy(x=>x) // sort
   .Select(newdate => newdate.ToString(culture.ShortDatePattern)) // back to string
   .ToList();

As Matt Johnson pointed out you really just need to parse in OrderBy - no need to convert back and forth:

var listOfSortedStringDates = Dates
   .OrderBy(v => DateTime.ParseExact(
          v.ToString(), culture.ShortDatePattern, CultureInfo.InvariantCulture))
   .ToList();

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Rather than converting, sorting, and converting back, you could sort without conversion using a custom comparison delegate, like this:

Dates.Sort((lhs, rhs) => {
    var lhsDate = DateTime.ParseExact(Convert.ToString(lhs), culture.ShortDatePattern, CultureInfo.InvariantCulture);
    var rhsDate = DateTime.ParseExact(Convert.ToString(rhs), culture.ShortDatePattern, CultureInfo.InvariantCulture);
    return lhsDate.CompareTo(rhsDate);
});

Upvotes: 4

Related Questions