I have the following program. My data types are all string. From the list I want to sort those entries that have numeric values. Those entries without numeric data will be always on the last items. Here's my code. Please help.
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; }
}
Based on my sample, I want to sort the items as
(for Lovely and Larry it doesn't matter for me how they are sorted as long as I got sorted correctly Drew to John).
Try using .TryParse()
instead, and assign max value to anything that can't be parsed
You can either use double.MaxValue
or double.PositiveInfinity
as default value. The latter is the greater of the two.
persons.OrderBy(x => double.TryParse(x.Position, out double d) ? d : double.PositiveInfinity)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With