Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq sort with Null values

I have a class with one string property and it can be null sometimes or it can be a integer number some times or it can be a string .

I want to sort on the basis of this property using LINQ with ascending order of integer values and all nono integer values next and null values in the end

How can I make a LINQ expression that handles the scenarios

Example

"1" ,NULL , "34", "6" ,"67",NULL ,"r45","j34" ,"s"  to be sorted as 

"1" "6" "34"  "67" "j34" "r45" "s" NULL NULL

I tried something like this but not really perfect the answer is

var licenseitems_master =  my master list 
var firstPart = licenseitems_master.Where(x => !String.IsNullOrEmpty(x.Page) && x.Page.All(char.IsDigit)).OrderBy(x => Convert.ToInt32(x.Page));
var secondPart = licenseitems_master.Where(x => !String.IsNullOrEmpty(x.Page) && !x.Page.All(char.IsDigit)).OrderBy(x => x.Page);
var thirdPart = licenseitems_master.Where(x => String.IsNullOrEmpty(x.Page)).ToList();
var sorted_items = firstPart.Union(secondPart).Union(thirdPart).ToList();

Can we make it as a single LINQ expression?

like image 883
Sebastian Avatar asked Sep 24 '26 19:09

Sebastian


1 Answers

You could also go for something like that.

First : TryParse to int, and order by that value (if you can't parse, replace the value by Int32.MaxValue, which will put these values at the end).

Second: put null at end.

Third: Order that result by "string" value

int outValue;
var result = input
                .OrderBy(m => Int32.TryParse(m, out outValue)
                    ? outValue
                    : Int32.MaxValue)
                .ThenBy(m => m == null)
                .ThenBy(m => m)
                .ToList();
like image 87
Raphaël Althaus Avatar answered Sep 27 '26 09:09

Raphaël Althaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!