我正在编写一些查询Visual Studio对象模型的代码。

我看到Exists集合对象上没有Projects方法,但是我喜欢防御性编程,并且不依赖try catch块。所以我看到AsQueryable()对象上有Projects,我想知道这是否有帮助。

我可以看到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”的定义,找不到扩展方法“ Where”,该扩展方法接受“ IQueryable”类型的第一个参数(是否缺少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);
        }
    }
}

最佳答案

EnvDTE.Projects不是“通用集合”,它仅实现非通用IEnumerable(https://docs.microsoft.com/en-us/dotnet/api/envdte.projects?view=visualstudiosdk-2017

您需要先使用IEnumerable<T>Cast转换为通用OfType

   var query = sol.Projects.OfType<EnvDTE.Project>().Where(proj => proj.Name == project);

10-07 19:11
查看更多