When dealing with different data structures in LINQ, you can extract a single piece of data in two primary ways: Single
or First
.
Single/SingleOrDefault()
Single
returns a single result. If there is more than one result, it will throw an exception. Use this only if you are sure the data structure that you are dealing with only has a single result.
SingleOrDefault()
also returns a single result. It will still throw an exception if there is more than one result, but will return a default value if the data structure is empty. For example, if you have a data structure that contains elements of type int
and it is empty, 0
will be returned. If it is a data structure that contains elements of type string
and it is empty, null
will be returned.
First/FirstOrDefault()
First
will return the first result in a data structure with multiple elements. An exception will be thrown if the data structure is empty. First
should be used when there is a data structure with more than one element contained within it.
FirstOrDefault()
will return the first result in a data structure with multiple elements. If the data structure is empty, it will return a default value depending on the data type of the data structure. For example, if you have a data structure that contains elements of type int
and it is empty, 0
will be returned. If it is a data structure that contains elements of type string
and it is empty, null
will be returned.