wpf 无法将类型“System.Linq.IQueryable<Database.Table>”隐式转换为“bool”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17094894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot implicitly convert type 'System.Linq.IQueryable<Database.Table>' to 'bool'
提问by KeyboardFriendly
Hello I am getting the error
你好我收到错误
Cannot implicitly convert type 'System.Linq.IQueryable<Database.Table>' to 'bool'
From this piece of code
从这段代码
foreach (var file in files)
{
if (context.SomeTables.Where(p => p.FileName == System.IO.Path.GetFileName(file)))
{
//Do Something //above I am trying to compare if the filename in the db table
//is equal to the GetFileName being passed in but it throwing
//the error
}
回答by Robert Harvey
context.SomeTables.Where(p => p.FileName == System.IO.Path.GetFileName(file))
returns an IQueryable, not a bool. You need something that returns a bool, like
返回一个IQueryable,而不是一个bool。你需要一些返回 a 的东西bool,比如
context.SomeTables.Any(p => p.FileName == System.IO.Path.GetFileName(file))
as your condition for the ifstatement.
作为if声明的条件。
回答by Jonesopolis
To be more insightful, the if statement needs an expression that evaluates to true or false. If you mouse over the Where() method you can see what it will be returning, which is a System.Linq.IQueryable.
为了更有洞察力,if 语句需要一个计算结果为真或假的表达式。如果将鼠标悬停在 Where() 方法上,您可以看到它将返回的内容,即 System.Linq.IQueryable。
Your error message is saying it needs a bool (true, false) but it's recieving System.Linq.IQueryable
您的错误消息说它需要一个 bool (true, false) 但它正在接收 System.Linq.IQueryable
Replacing Where() with Any() will return a boolean.
用 Any() 替换 Where() 将返回一个布尔值。
回答by JSJ
As Robert suggested in his answer of using Any()in above case. this is good if you are just looking to compare true or false. In my opinion you might be looking for the object which you are comparing against the file object.
正如罗伯特在他在上述情况下使用Any() 的回答中所建议的那样。如果您只是想比较真假,这很好。在我看来,您可能正在寻找与文件对象进行比较的对象。
So you can also try like this.
所以你也可以这样试试。
foreach (var file in files)
{
var tempvalue = context.SomeTables.Where(p => p.FileName == System.IO.Path.GetFileName(file)).FirstOrDefault();
if (tempvalue !=null)
{
//here you get both of the object file as well as compairer value.
}
}
This will give you the opportunity to get the tempvalue for further tasks. by this you get the value in single attempt and perform multiple tasks as well.
这将使您有机会获得用于进一步任务的临时值。通过这种方式,您可以在一次尝试中获得价值并执行多项任务。

