1

I have an array of (always 4) objects, which I need to order by descending value of an object member.
I had thought to order it as

Array = Array.OrderByDescending(p => p.Val)

This fell over when one of the values was null, of course. So what I am aiming for, but my LINQ is not up to, is:

Array = Array.OrderByDescending(p => if( p != null ) p.Val; else float.MinValue)

How can I accomplish this ordering without having to delete and later re-add the null value? Thanks for your help.

4

3 回答 3

12

Use the ternary conditional operator:

Array = Array.OrderByDescending(p => p != null ? p.Val : float.MinValue)

Per the comments below, the reason you can't use the if/else is because the body of the lambda (the stuff to the right of p =>) must be an expression, unless you surround the whole thing with curly braces. So to illustrate, you could also use the if/else if you wanted:

Array = Array.OrderByDescending(p => 
{
    if (p != null) return p.Val; 
    else return float.MinValue;
});

But clearly more verbose.

于 2012-06-05T20:06:35.863 回答
2

I'm not sure what objects/types you're working with, but perhaps try a ternary operator like the following:

Array = Array.OrderByDescending(p => p == null ? float.MinValue : p.Val)
于 2012-06-05T20:07:33.783 回答
0

Use this operator:

Array = Array.OrderByDescending( p => p ?? float.MinValue)   
于 2013-10-25T07:58:36.793 回答