10. Element Operations Flashcards
What does the First
extension method do?
Returns the first element of a sequence.
What does the Last
extension method do?
Returns the last element of a sequence.
What does the FirstOrDefault
extension method do?
Returns the first element of a sequence if it’s not empty. If it is, returns the default value for the sequence’s element type.
What happens if you call First
or Last
method on an empty sequence?
An exception gets thrown.
What does the LastOrDefault
extension method do?
Returns the last element of a sequence if it’s not empty. If it is, returns the default value for the sequence’s element type.
What does the ElementAt
extension method do, why would you want to use it, and why would you not?
- Returns the element at a specified index in a sequence.
- Because Enumerable is more generic, and a collection represented by enumerable may not have an indexer.
- Don’t use ElementAt() where you can use an index. It’s probably not going to be as efficient.
What happens if you pass the ElementAt
extension method an index that’s greater than or equal to the length of the sequence that’s being operated on?
It throws an exception.
What does the ElementAtOrDefault
extension method do?
Returns the element at a specified index in a sequence if it exists. If not, it returns the default value for the sequence’s element type.
What does the Single
extension method do and when would it throw an exception?
It returns the only element in a sequence that returns true when passed to a specified predicate function. If more than one elements return true, it throws an exception.
What does the SingleOrDefault
extension method do and when would it throw an exception?
It returns the only element in a sequence that returns true when passed to a specified predicate function. If no elements do, it returns the default value for the element type. If more than one elements do, it throws an error.