Search code examples
c#linqlinq-to-objects

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.


Solution

  • DefaultIfEmpty method should help:

    int new_id = C_Movement.list.Select(x => x.id).DefaultIfEmpty(-1).Max()+1;