0

I have a problem with my code. I'm doing a crud with C# and I'm tring to find a student by id. In case you do not find any match I want to send a message saying that there is no student with that id. How can I do that?

I tried with a simple while:

while(i < count && !found)
{
    s = studentList[i];
    if (id.Equals(s.IdStudent))
    {
        found = true;
        student = s;
    }
    i++;
}

if (found == false)
{
    System.Console.WriteLine("There is no match");
}

And I'm trying this:

student = studentList.First(i => i.IdStudent == id);
if(student == null)
{
    System.Console.WriteLine("There is no match");
}

It seems to be fine but when executing and using an id that is not in the list it tells me that I do not control the exception.

double-beep
  • 5,031
  • 17
  • 33
  • 41

2 Answers2

1

If you use First, the expectation is that there is at least one element in the sequence. Using FirstOrDefault should be fine for your case.

Janez Lukan
  • 1,439
  • 1
  • 12
  • 28
1

You need to use FirstOrDefault instead of First.

Amir Molaei
  • 3,700
  • 1
  • 17
  • 20