一个linq的编译异常,怎么改呢
一个linq的编译错误,如何改呢
如题,我使用C#的linq查询语句形式,在where语句当中写了一个lambda匿名函数,但是这个函数编译不过:
Error 1 Cannot convert lambda expression to type 'bool' because it is not a delegate type
这到底是为什么呢,where语句难道不支持lambda?
我用vs2013,谢谢
------解决思路----------------------
(from x in Directory.GetFileSystemEntries(path)
where new Func<string, bool>(y =>
{
Console.WriteLine(y);
return true;
})(x)
select x).Count();
如果你一定要这么玩儿的话。
------解决思路----------------------
如果你把它写为
(from x in Directory.GetFileSystemEntries(path)
where (y => { Console.WriteLine(y); return true; })
select x).Count();
从编译器给出的提示其实很清晰地看出“为什么不能编译”。虽然你写了一个lamda表达式,但是谁知道你的lamda表达式的委托声明是什么呢?Linq的每一个方法,例如where的部分,都有Delete原型声明的,不是空洞地说一声“lamda表达式”就行了。
------解决思路----------------------
你声明了一个委托,但where要的是执行,不是声明
------解决思路----------------------
要通过编译的方法很多,sp1234的方法之外,还可以用
(from x in Directory.GetFileSystemEntries(path).Where(y => { Console.WriteLine(y); return true; })
select x).Count();
但是这么做我觉得毫无意义和必要。不要滥用linq。
如题,我使用C#的linq查询语句形式,在where语句当中写了一个lambda匿名函数,但是这个函数编译不过:
class Program
{
string path = "d:\\";
void test()
{
(from x in Directory.GetFileSystemEntries(path)
where (x => { Console.WriteLine(x); return true; })
select x).Count();
}
static void Main(string[] args)
{
new Program().test();
}
}
Error 1 Cannot convert lambda expression to type 'bool' because it is not a delegate type
这到底是为什么呢,where语句难道不支持lambda?
我用vs2013,谢谢
------解决思路----------------------
(from x in Directory.GetFileSystemEntries(path)
where new Func<string, bool>(y =>
{
Console.WriteLine(y);
return true;
})(x)
select x).Count();
如果你一定要这么玩儿的话。
------解决思路----------------------
如果你把它写为
(from x in Directory.GetFileSystemEntries(path)
where (y => { Console.WriteLine(y); return true; })
select x).Count();
从编译器给出的提示其实很清晰地看出“为什么不能编译”。虽然你写了一个lamda表达式,但是谁知道你的lamda表达式的委托声明是什么呢?Linq的每一个方法,例如where的部分,都有Delete原型声明的,不是空洞地说一声“lamda表达式”就行了。
------解决思路----------------------
你声明了一个委托,但where要的是执行,不是声明
------解决思路----------------------
要通过编译的方法很多,sp1234的方法之外,还可以用
(from x in Directory.GetFileSystemEntries(path).Where(y => { Console.WriteLine(y); return true; })
select x).Count();
但是这么做我觉得毫无意义和必要。不要滥用linq。