-2

If i = {1,2} no problem.

If iId = 3 (or anything else) why does .First() crash.

public class C { public int ID, public string nam }
int i = 3;
C c = new List<C>;
c.Add(new C{ID = 1, nam="hello" });
c.Add(new C{ID = 2, nam=world" });
C r = c.First(e => e.ID.Equals(i));

The exception is:

InvalidOperationException was unhandled by user code

Sequence contains no matching element

I would think the least the expression would have to do is return null. Instead it crashed.
That makes no sense to me. A returned null would make sense to me.

What do you do to work around this? What is your best practice?

Community
  • 1
  • 1
Steve
  • 905
  • 1
  • 8
  • 32

2 Answers2

2

Change from First(e => e.ID.Equals(i)) to FirstOrDefault(e => e.ID.Equals(i)), then you'll get nulls (since default(C) is null, as that is the default for a reference type) which you can handle how you see fit, rather than having your app crash.

Here's the MDSN link to FirstOrDefault, if you need any more info/examples:
https://msdn.microsoft.com/en-us/library/bb340482(v=vs.110).aspx

Broots Waymb
  • 4,713
  • 3
  • 28
  • 51
0

I tend to agree .First() could be a little more frendly but you get what you want by using .FirstOrDefault()

When to use .First and when to use .FirstOrDefault with LINQ?

Community
  • 1
  • 1
Steve
  • 905
  • 1
  • 8
  • 32