Lambda string by dates with number

How to sort this?

I have a list of strings 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

The conclusion should be: the one that does not have an account should be the last, and the top one, then 1, and the dates should be sorted in ascending order.

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 in descending order

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 for this you will need to change other methods that will require a lot of work.

Hello

+4
source share
5 answers

Here is the @Guru Stron 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;
}
+2
source

, , . : , ( 0, < 11), yourList.OrderBy(s=> f1(s)).ThenByDescending(s=> f2(s))

+3

, , ;

    edates =
        edates.OrderBy(x => 
               DateTime.ParseExact(x.Substring(0, 10), "MM-dd-yyyy", 
               CultureInfo.InvariantCulture))
            .ThenByDescending(x => x.Substring(10))
            .ToList();
+1

>= 10.

" " ( , , L2S/EF LINQ), . , , , ( IComparer ) - , " " .

DateTime OrderableItem (string e) {
    var date = e.Substring(0, 10);
    return DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture)
}

int OrderableCount (string e) {
    var m = Regex.Match(e, @"-count=(\d+)$", RegexOptions.IgnoreCase);
    return m.Success
        ? int.Parse(m.Groups[1].Value)
        : 0;
}

var res = seq.OrderBy(OrderableDate)
             .ThenBy(OrderableCount);

, .

0

You must use a real class to simplify things and have the right idea. However, you can use the LINQ query syntax and use a clause letto store the result of dividing the text into a space and an equal sign. If the separation result has more than one element, we can assume that the account exists. Then we order by date (after parsing it), and then by parsing the counter (descending).

Try this approach:

string[] inputs = 
{
    "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"
};

var query = from input in inputs
            let split = input.Split(' ', '=')
            let count = split.Length > 1 ? int.Parse(split[2]) : 0
            orderby DateTime.Parse(split[0]), count descending
            select input;

foreach (var item in query)
{
    Console.WriteLine(item);
}
0
source

All Articles