没有 Exists 方法,所以我想使用 AsQueryable 进行防御性编程

No Exists method so I want to use AsQueryable for defensive programming

我正在编写一些查询 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' 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?)

它只是缺少参考吗?这是最小的可重新创建代码 ...

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 不是 'generic collection',它只实现了 non-generic IEnumerable (https://docs.microsoft.com/en-us/dotnet/api/envdte.projects?view=visualstudiosdk-2017)

您需要先转换为通用 IEnumerable<T>,使用 CastOfType:

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