How to check the length of the result, where

List<object> _list = new List<object>(); public object Get => _list.Where( x => x.GetType() == typeof( int ) ).First(); 

Using the above code will System.InvalidOperationException when the length of Where is zero.

  public object Get2 { get { var where = _list.Where( x => x.GetType() == typeof( int ) ); if( 0 < where.Count() ) { return where.First(); } return null; } } 

So, I use it to fix this, but is there a way to make the code cleaner?

+4
source share
5 answers

FirstOrDefault will be what you are looking for:

 public object Get => _list.FirstOrDefault( x => x.GetType() == typeof(int)) 

When you encounter First() NullReferenceException if the collection is null as FirstOrDefault will give you a default value if there is nothing to choose from.

Here you can find topics that compare .First and FirstOrDefault and describe scenarios in which you need to use them.

+5
source

Use FirstOrDefault to get null as the return value when all else fails.

 public object Get => _list.FirstOrDefault( x => x.GetType() == typeof( int ) ); 
+4
source

instead of First()

  public object Get => _list.Where( x => x.GetType() == typeof( int ) ).First(); 

Use FirstOrDefault()

 public object Get => _list.Where( x => x.GetType() == typeof( int ) ).FirstOrDefault(); 
+2
source

Use FirstOrDefault() instead of First() . Because First() returns the first element of the sequence and returns the first element of the sequence. FirstOrDefault () does not throw an exception if there is no element in the table.

 public object Get => _list.Where( x => x.GetType() == typeof( int ) ).FirstOrDefault (); 
0
source

FirstOrDefault: returns the first element of the sequence or the default value if the element is not found. Throws an exception: Only if the source is null. Use when: When more than 1 item is expected, and you only want the first.

0
source

Source: https://habr.com/ru/post/1270767/


All Articles