gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:34 25 4
gpt4 key购买 nike

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

我看到 Projects 集合对象上没有 Exists 方法,但我确实喜欢防御性编程而不依赖于 try catch block 。所以我看到 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 不是“通用集合”,它仅实现非通用 IEnumerable ( https://learn.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); 

关于c# - 没有 Exists 方法,所以我想使用 AsQueryable 进行防御性编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48855300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com