Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the result length of where

Tags:

c#

 List<object> _list = new List<object>();

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

Using the above code will cause a 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 am using it to fix this, but is there a way to make the code cleaner?

like image 511
Lim Avatar asked Dec 18 '22 05:12

Lim


1 Answers

FirstOrDefault will be the thing that you are looking for:

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

As you faced the First() raise NullReferenceException if the collection is null where as the FirstOrDefault will give you the default value in case there is nothing to select.

Here you can find threads that compare .First and FirstOrDefault and describe the scenarios where you need to use them

like image 139
sujith karivelil Avatar answered Jan 02 '23 21:01

sujith karivelil