Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ "MaxOrDefault"?

I'm new to LINQ. I need to compute new_id as follows:

public class C_Movement {   public int id=-1;   public static ObservableCollection<C_Movement> list=new ObservableCollection<C_Movement>();   // ... }  int new_id = (C_Movement.list.Count==0) ? 0 : C_Movement.list.Max(x => x.id)+1; 

Is there a LINQ way to compact that expression, so that I don't have to use the ? : structure? The problem is that, when C_Movement.list contains no elements, C_Movement.list.Max(x => x.id) returns null (and I would like it to return -1, instead).

Thank you.

like image 453
Telaclavo Avatar asked Mar 30 '12 17:03

Telaclavo


1 Answers

DefaultIfEmpty method should help:

int new_id = C_Movement.list.Select(x => x.id).DefaultIfEmpty(-1).Max()+1; 
like image 186
Snowbear Avatar answered Oct 07 '22 10:10

Snowbear