Is it possible to use a LINQ query to return a single object instead of a list?
User user = (from User u in users
where u.id == 5
select u);
Yes,
User user = (from User u in users
where u.id == 5
select u).Single()
This will throw and exception if more than one element is returned by the query.
If you only want the first element:
User user = (from User u in users
where u.id == 5
select u).First()
Use SingleOrDefault() and FirstOrDefault() to return null for reference types when no element exists.
Use one of:
.Single() // return a single
.SingleOrDefault() // return a single or the default value if there are no matches
.First() // return the first object it encounters that matches
.FirstOrDefault() // return the first object it encounters that matches, or the default value if no matches
.Single() and .SingleOrDefault() will throw an exception if there are multiple matches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With