【问题标题】:No Exists method so I want to use AsQueryable for defensive programmingNo Exists 方法,所以我想使用 AsQueryable 进行防御性编程
【发布时间】: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&lt;EnvDTE.Project&gt; 时会发生什么?
  • 那么,它们是什么?更好地记录你的情况,也许写一个minimal reproducible example
  • @SMeaden,您甚至不需要 IQueryable。 IEnumerable 应该可以很好地使用 Linq to Objects 'Where' 方法。

标签: c# linq defensive-programming asqueryable


【解决方案1】:

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

您需要先转换为通用IEnumerable&lt;T&gt;,使用CastOfType

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

【讨论】:

  • 正如我之前所说,在这种情况下无需通过IQueryable,它只会使其(可能不明显,但仍然)变慢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多