Tuesday, March 29, 2022

c# - How to solve error "Sequence contains no elements" by Max() LINQ

This error occurs when the list is empty - no items are suitable for conditions.
int xCalc = _layoutManager.Items
  .Where( x=> x.ParentObject == this.ParentObject )
  .Where( x=> x.LayoutRelativePosition == LayoutRelativePositionEnum.RIGHT )
  .Where( x=> x.IDOrder < this.IDOrder )              
  .Max( x=> x.xCalc + x.heightCalc );
Above Max() version returns in that situation (no items) error "Sequence contains no elements". For solution you can use this format of the Max() function:
int xCalc = _layoutManager.Items
  .Where( x=> x.ParentObject == this.ParentObject )
  .Where( x=> x.LayoutRelativePosition == LayoutRelativePositionEnum.RIGHT )
  .Where( x=> x.IDOrder < this.IDOrder )
  .Select(x => x.xCalc + x.heightCalc )
  .DefaultIfEmpty()          
  .Max();

No comments:

Post a Comment