Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Sort Numeric Data Only But Retain The List Intact

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

  1. Drew
  2. Rose
  3. Peter
  4. John
  5. Lovely
  6. Larry

(for Lovely and Larry it doesn't matter for me how they are sorted as long as I got sorted correctly Drew to John).

like image 696
Jobert Enamno Avatar asked Dec 18 '22 14:12

Jobert Enamno


1 Answers

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)
like image 176
Innat3 Avatar answered Dec 24 '22 00:12

Innat3