ERR
ERR

Reputation: 415

Splitting the string and sorting - Linq

I have a list "Sites" with one of the items as "Year". It is defined as a string and is in the format "MM/yyyy". Data for "Year" is

01/2012
04/2012
01/2013
06/2012

I understand that I can use DateTime.Parse to convert the string and sort it. But I want to split the string and do the sort using linq. Is there a possibility of splitting the MM and yyyy, sorting it?

Upvotes: 0

Views: 881

Answers (2)

Phil1970
Phil1970

Reputation: 2623

Well, as indicated in the other answer, you can do it. My answer use an anonymous struct instead so the sorting should be more efficient.

method1Result show what I would have done (assuming that the data is always valid). The main advantage is that you have DateTime object so it would be easier to use afterward.

method2Result do not use DateTime.Parse as required in the question. However, it lead to longer code and the result is less usable (and if you need to return it, you would have to replace anonymous struct by one you define.

var data = new string[]
{
    "01/2012",
    "04/2012",
    "01/2013",
    "06/2012",
};

var method1Result = data
    .Select(x => DateTime.Parse(x)).OrderBy(x => x);

var method2Result = data
    .Select(x => 
        { 
            var t = x.Split('/'); 
            return new { 
                year = int.Parse(t[1]), 
                month = int.Parse(t[0]) }; 
            })
    .OrderBy(x => x.year)
    .ThenBy(x => x.month);

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Absolutely, this can be easily done. However, this is inefficient, because you would have to do a split on each comparison:

.OrderBy(yearMonthStr => {
    var tokens = yearMonthStr.Split('/');
    return int.Parse(tokens[0]) + 100*int.Parse(tokens[1])
})

Upvotes: 1

Related Questions