Can I use a TryParse inside Linq Comparable?

后端 未结 5 1466
野趣味
野趣味 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:41

    That won't produce the expected results b/c TryParse returns a bool rather than int. The easiest thing to do is create a function that returns an int.

    private int parseNote(string note) 
    {   
      int num;   
      if (!Int32.TryParse(note, out num)) 
      {
        num = int.MaxValue; // or int.MinValue - however it should show up in sort   
      }
    
      return num; 
    }
    

    call that function from your sort

    Documenti = Documenti
        .OrderBy(o => parseNote(o.Note))
        .ToList();
    

    you could do it inline too, but, i think a separate method makes the code more readable. i'm sure the compiler will inline it, if it's an optimization.

提交回复
热议问题