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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With