Can I use a TryParse inside Linq Comparable?

后端 未结 5 1465
野趣味
野趣味 2020-12-03 10:44

A sort of:

Documenti = Documenti
    .OrderBy(o => string.IsNullOrEmpty(o.Note))
    .ThenBy(o => Int32.TryParse(o.Note))
    .ToList();
5条回答
  •  攒了一身酷
    2020-12-03 11:37

    You can actually put much more complex logic in the lambda expression:

    List Documenti = new List() {
            new Doc(""),
            new Doc("1"),
            new Doc("-4"),
            new Doc(null) };
    
    Documenti = Documenti.OrderBy(o => string.IsNullOrEmpty(o.Note)).ThenBy(o => 
    {
        int result;
        if (Int32.TryParse(o.Note, out result))
        {
            return result;
        } else {
            return Int32.MaxValue;
        }
    }).ToList();
    
    foreach (var item in Documenti)
    {
        Console.WriteLine(item.Note ?? "null");
        // Order returned: -4, 1, , null
    }
    

    Remember, o => Int32.TryParse(...) is just a shorthand for creating a delegate that just takes in o as a parameter and returns Int32.TryParse(...). You can make it do whatever you want as long as it still is a syntacticly correct method with the correct signature (ex, all code paths return an int)

提交回复
热议问题