How do I rewrite this line using method syntax?

I'm working with SMO and I have this line of code:

var results = (from User user in database.Users
    where user.LoginType == LoginType.WindowsUser
    select new { user.Name, user.Login }).ToList();

But for whatever reason, I cannot write the query like this:

var results = database.Users
              .Where(user => user.LoginType == LoginType.WindowsUser)
              .Select(user => new { Name = user.Name, Login = user.Login })
              .ToList();

The error I get is 'UserCollection' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'UserCollection' could be found (are you missing a using directive or an assembly reference?)

But as far as as I can see, both these statements are identical.

Why does this happen?

Jon Skeet
people
quotationmark

No, they're very slightly different. Because you've got an explicitly-typed range variable here:

from User user in database.Users

your query is equivalent to:

var results = database.Users
                      .Cast<User>();
                      .Where(user => user.LoginType == LoginType.WindowsUser)
                      .Select(user => new { user.Name, user.Login })
                      .ToList();

Presumably your UserCollection type implements IEnumerable, but not IEnumerable<User> - which is why you need the cast.

You can provoke the same error with a query expression by leaving the range variable implicitly typed:

// This will fail
var results = (from user in database.Users
               where user.LoginType == LoginType.WindowsUser
               select new { user.Name, user.Login }).ToList();

people

See more on this question at Stackoverflow