Saturday, 9 December 2017
c# - When to use .First and when to use .FirstOrDefault with LINQ?
Answer
Answer
I've searched around and haven't
really found a clear answer as to when you'd want to use .First
and when you'd want to use .FirstOrDefault
with
LINQ.
When would
you want to use.First
? Only when you'd want to catch the
exception if no results where
returned?var result =
List.Where(x => x ==
"foo").First();And
when would you want to use.FirstOrDefault
? When you'd always
want the default type if no
result?var result = List.Where(x
=> x ==
"foo").FirstOrDefault();And
for that matter, what about
Take?var result = List.Where(x
=> x ==
"foo").Take(1);
Answer
I would use
First()
when I know or expect the sequence to have at least one
element. In other words, when it is an exceptional occurrence that the sequence is
empty.
Use
FirstOrDefault()
when you know that you will need to check
whether there was an element or not. In other words, when it is legal for the sequence
to be empty. You should not rely on exception handling for the check. (It is bad
practice and might hurt performance).
Finally,
the difference between First()
and
Take(1)
is that First()
returns the
element itself, while Take(1)
returns a sequence of elements
that contains exactly one element.
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I have a method in repository with this implementation which returns a Task Task > GetAllAppsRequestAsync(); I write the getter which cal...
No comments:
Post a Comment