I was searching for a solution to permform a linq query and ignore case. I found this:
m_context.Users.SingleOrDefault(u => string.Compare(u.UserName, username, StringComparison.InvariantCultureIgnoreCase) == 0);
It search for a user object based on the username provided, ignoring case. It works, that’s not the question here, but when analysing the code it seems strange to me. I mean, inside the linq, we have the string.Compare(…,…,…) returning an integer. So what? How is it managed by linq (SingleOrDefault)?
Thanks for your help.
You are passing a predicate into the
SingleOrDefaultmethod. The predicate evaluates to true or false, and this method returns the single element in the sequence that satisfies that predicate.This is a
Func<User, bool>predicate, which means it is a function that accepts a User as an argumentuand returns a boolean value as a result of thestring.Compare(...) == 0evaluation. The single element in the sequence of users to satisfy this condition is then returned. If more than one satisfies the predicate, it is an error. If less than one satisfies the predicate, you get the default value for the type, which for a reference type is simply null.Think of it as very roughly
The above is again just my rough draft of what the method does, not the actual implementation. If you’re interested in a more in-depth investigation of linq-to-objects implementations, consider reading Jon Skeet’s Edulinq series, where he goes through and reimplements every (give or take) method and explains it along the way. Again, that’s not the actual source code of the library, but it is very educational.