0

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...

2 Answers 2

4

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);
});
Sign up to request clarification or add additional context in comments.

Comments

2

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();

2 Comments

Why not just do the parse in the OrderBy? Then you don't have to convert twice.
@MattJohnson good point - separate steps are nicer to explain, but really more work. Also OrderBy caches all keys - so there is no extra calls to Parse anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.