Linq - Order by number then letters

前端 未结 2 763
野趣味
野趣味 2020-12-16 03:19

I have a list of strings, and these strings contain numbers and words.

What I wanted to do is order it by the numbers (numeric order) followed by the words (alphabet

2条回答
  •  臣服心动
    2020-12-16 03:46

    This solution attempts parsing once for each value.

    List voltage = new List() { "1", "5", "500" , "LT", "RT", "400" };
    
    List result = voltage
      .OrderBy(s =>
      {
        int i = 0;
        return int.TryParse(s, out i) ? i : int.MaxValue;
      })
      .ThenBy(s => s)
      .ToList();
    

提交回复
热议问题