LINQ仅对数字数据进行排序但保持列表完整

Job*_*mno 4 c# linq sorting list

我有以下程序。我的数据类型都是字符串。从列表中,我想对那些具有数值的条目进行排序。那些没有数字数据的条目将始终位于最后一项。这是我的代码。请帮忙。

 class Program
{
    static void Main(string[] args)
    {
        var persons = new List<Person>();
        persons.Add(new Person { Name = "John",   Position = "100" });
        persons.Add(new Person { Name = "Peter",  Position = "78"  });
        persons.Add(new Person { Name = "Larry",  Position = "NA"  });
        persons.Add(new Person { Name = "Lovely", Position = ""    });
        persons.Add(new Person { Name = "Rose",   Position = "50"  });
        persons.Add(new Person { Name = "Drew",   Position = "34"  });

        //Help me do the sorting for position that is a number. Priority in sorting are positions which are numbers
        var sortedPersons = persons.OrderBy(x=>double.Parse(x.Position)).ToList();
        foreach (var person in sortedPersons)
            Console.WriteLine("Name: {0}, Position: {1}", person.Name, person.Position);
        Console.ReadLine();
    }
}
public class Person
{
    public string Name { get; set; }
    public string Position { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

根据我的示例,我想将项目排序为

  1. 德鲁
  2. 玫瑰
  3. 彼得
  4. 约翰
  5. 迷人的
  6. 拉里

(对于 Lovely 和 Larry,只要我正确排序 Drew to John,它们的排序方式对我来说并不重要)。

Inn*_*at3 7

尝试使用.TryParse(),并将最大值分配给无法解析的任何内容

您可以使用double.MaxValuedouble.PositiveInfinity作为默认值。后者是两者中较大的一个。

persons.OrderBy(x => double.TryParse(x.Position, out double d) ? d : double.PositiveInfinity)
Run Code Online (Sandbox Code Playgroud)