4
 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?

Lim
  • 190
  • 1
  • 10

5 Answers5

5

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

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
4

Use FirstOrDefault to get null as return value, when nothing got matched.

public object Get => _list.FirstOrDefault( x => x.GetType() == typeof( int ) );
Ben
  • 763
  • 1
  • 5
  • 14
2

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

Use FirstOrDefault() instead of First(). Because, First() returns first element of sequence and it returns first element of sequence. FirstOrDefault () does not throws exception when There is no element present in table.

public object Get => _list.Where( x => x.GetType() == typeof( int ) ).FirstOrDefault ();
Alsamil Mehboob
  • 384
  • 2
  • 6
  • 24
0

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

Ben
  • 1
  • 1