Megrez7
Megrez7

Reputation: 1477

Dealing with LINQ to Objects when object not found

I am using Linq statement as per below to find student name by its ID. It works fine. However there are cases where there is no student with given ID. In those cases an error is thrown "Object reference not set to an instance of an object."

How to efficiently deal with this problem?

Dim Name As String = Students.FirstOrDefault(Function(Student) Student.ID = "NO00007").Name

Upvotes: 1

Views: 273

Answers (2)

Fabio
Fabio

Reputation: 32455

As usually answer is "it depend" - it depend on how you will use result you will get

If you want get some "default"/empty string instead of name when collection doesn't contain item

Dim result = Students.Where(Function(student) student.ID = "NO00007").
                      Select(Function(student) student.Name).
                      DefaultIfEmpty(String.Empty).
                      First()

Almost same approach if you want to get some "empty" object instead of null

Dim resultStudent = Students.Where(Function(student) student.ID = "NO00007").
                             DefaultIfEmpty(New Student With { .Name = "empty" }).
                             First()

From performance point of view approach above are same as FirstOrDefault - but provide little bid better readability(subjective of course)

Upvotes: 2

NetMage
NetMage

Reputation: 26927

If you are satisfied with Name being null if there is no matching student, you can use the null conditional operator for member access:

Dim Name As String = Students.FirstOrDefault(Function(Student) Student.ID = "NO00007")?.Name

Upvotes: 4

Related Questions