In Link to Sql, this works fine:
User user = this.dataContext.Users.FirstOrDefault(p => p.User_ID == loginID);
However, I would like to search using conditions like:
User user = this.dataContext.Users.FirstOrDefault( p => p.User_ID == 250 && p => p.UserName == "Jack");
What's the correct way to do this?
Thanks.
When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault. When you want a default value if the result set contains no record, use FirstOrDefault.
FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.
Use First() when you are sure that a query must return a record, and use FirstOrDefault() when you are not sure whether it will return a record or not.
FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result. Single() asserts that one and only one element exists in the sequence. First() simply gives you the first one.
var user = this.dataContext.Users.FirstOrDefault( p => p.User_ID == 250 && p.UserName == "Jack");
The p =>
at the beginning counts for the whole expression. The syntax used here is a shorthand for
(p) => { return p.User_ID == 250 && p.UserName == "Jack"; }
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