【发布时间】:2018-07-29 01:07:18
【问题描述】:
我正在编写一些查询 Visual Studio 对象模型的代码。
我看到 Projects 集合对象上没有 Exists 方法,但我确实喜欢防御性编程,而不是依赖于 try catch 块。所以我看到Projects 对象上有AsQueryable(),我想知道这是否有帮助。
我可以看到here我想写的那种代码,
IQueryable<Student> query =
objStudent.AsQueryable().Where(student => student.Name.Contains("Alavala"));
但对我来说会是这样的
IQueryable<EnvDTE.Project> query =
sol.Projects.AsQueryable().Where(proj => proj.Name=project);
但这不会编译并给出错误消息
“IQueryable”不包含“Where”的定义,并且找不到接受“IQueryable”类型的第一个参数的扩展方法“Where”(您是否缺少 using 指令或程序集引用?)
只是缺少参考吗?这是最小的可重新创建代码...
using System.Linq;
using System.Runtime.InteropServices;
namespace AsQueryableConsoleApp
{
class Program
{
static void Main(string[] args)
{
/* ensure the solution is running in a separate instance of Visual Studio 2017 */
string solution = @"C:\Users\Simon\source\repos\WebApplication1\WebApplication1.sln";
string project = "WebApplication1";
//string projectItem = "WebForm1.aspx";
object objSol = Marshal.BindToMoniker(solution); /* should bind if running */
EnvDTE.Solution sol = (EnvDTE.Solution)objSol; /* does a cast */
/* next line does not compile with error message
Error CS1061
'IQueryable' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?) AsQueryableConsoleApp
*/
IQueryable<EnvDTE.Project> query = sol.Projects.AsQueryable().Where(proj => proj.Name = project);
}
}
}
【问题讨论】:
-
是否添加了以下指令:
using System.Linq;? -
添加后有效吗?
-
当您使用
var而不是IQueryable<EnvDTE.Project>时会发生什么? -
那么,它们是什么?更好地记录你的情况,也许写一个minimal reproducible example
-
@SMeaden,您甚至不需要 IQueryable。 IEnumerable 应该可以很好地使用 Linq to Objects 'Where' 方法。
标签: c# linq defensive-programming asqueryable