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)
根据我的示例,我想将项目排序为
(对于 Lovely 和 Larry,只要我正确排序 Drew to John,它们的排序方式对我来说并不重要)。
尝试使用.TryParse()
,并将最大值分配给无法解析的任何内容
您可以使用double.MaxValue
或double.PositiveInfinity
作为默认值。后者是两者中较大的一个。
persons.OrderBy(x => double.TryParse(x.Position, out double d) ? d : double.PositiveInfinity)
Run Code Online (Sandbox Code Playgroud)