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();

Monday, March 21, 2022

c# - How get last x chars from string by LINQ

One possibility (last 6 chars):
string s = "This is a text";
      
MessageBox.Show( s.Substring( s.Length - 6 ) );
Another possibility with LINQ support (last 6 chars):
string s = "This is a text";
      
MessageBox.Show( new string( s.TakeLast(6).ToArray() ) );