我正在使用SMO,我有这行代码:
var results = (from User user in database.Users
where user.LoginType == LoginType.WindowsUser
select new { user.Name, user.Login }).ToList();
但无论出于何种原因,我无法像这样编写查询:
var results = database.Users
.Where(user => user.LoginType == LoginType.WindowsUser)
.Select(user => new { Name = user.Name, Login = user.Login })
.ToList();
我得到的错误是'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?)
但据我所知,这两种说法都是相同的。
为什么会这样?
答案 0 :(得分:8)
不,他们非常轻微不同。因为你在这里有一个显式类型的范围变量:
from User user in database.Users
您的查询相当于:
var results = database.Users
.Cast<User>();
.Where(user => user.LoginType == LoginType.WindowsUser)
.Select(user => new { user.Name, user.Login })
.ToList();
大概你的UserCollection
类型实现了IEnumerable
,但不是IEnumerable<User>
- 这就是你需要演员的原因。
您可以通过隐式键入范围变量来激活查询表达式的相同错误:
// This will fail
var results = (from user in database.Users
where user.LoginType == LoginType.WindowsUser
select new { user.Name, user.Login }).ToList();