Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FirstOrDefault with Multiple Conditions

Tags:

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.

like image 878
beaudetious Avatar asked Feb 03 '11 22:02

beaudetious


People also ask

Which is better SingleOrDefault or FirstOrDefault?

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.

What does FirstOrDefault return if not found?

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.

Should I use FirstOrDefault first?

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.

What is difference between FirstOrDefault and SingleOrDefault in Linq?

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.


1 Answers

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";       } 
like image 166
Femaref Avatar answered Oct 11 '22 12:10

Femaref