Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda string order by dates with number

Tags:

c#

lambda

linq

How to sort this?

I have List of string with values like this

11-03-2013
11-03-2013 -Count=2
11-03-2013 -count=1

11-04-2013 -Count=1
11-04-2013 -Count=2
11-04-2013

Output should be, The one without the count should be on the last and the top most should be 1 followed by 1 and dates should be ordered by ascending.

11-03-2013 -Count=2
11-03-2013 -count=1
11-03-2013

11-04-2013 -Count=2
11-04-2013 -Count=1
11-04-2013

I tried this code but this is sorting this by descending

var  edates= edates.OrderBy(e => e.Replace("-count=1", string.Empty).Replace("-count=2", string.Empty)).ToList(); 

I know that a simple class with properties can do the trick but doing that so would need to change other methods which would require a lot of work.

Regards

like image 975
Mico Avatar asked Mar 04 '26 23:03

Mico


2 Answers

it is because you compare strings not dates. Create two functions: first substrings date part and parses it and second substrings the count part and returns parsed count(or 0 if length < 11) and then yourList.OrderBy(s=> f1(s)).ThenByDescending(s=> f2(s))

like image 198
Guru Stron Avatar answered Mar 07 '26 13:03

Guru Stron


Here is @Guru Stron's solution in code

private static void sortList()
{
    var dates = getDates();
    var sorted = dates.OrderBy(f1).ThenByDescending(f2);
}

private static DateTime f1(string parse)
{
    return DateTime.Parse(parse.Substring(0, 10));
}

private static int f2(string parse)
{
    int sort;
    if (parse.Length > 10) int.TryParse(parse.Substring(18), out sort);
    else sort = 0;
    return sort;
}
like image 31
crthompson Avatar answered Mar 07 '26 11:03

crthompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!