linq - 在 where 子句中委托(delegate)

标签 linq delegates where-clause lambda

我可以定义一个委托(delegate)并像这样编写查询。

Func<string, bool>   filter  = s => s.Length == 5;

IEnumerable<string> query = names.Where(filter)                                  
                                 .Select(x => x.ToUpper());

我的问题是,如果 Func<T, TResult>是一个将字符串作为参数并返回 bool 值的委托(delegate),为什么我不能说:
delegate bool D(string s);
D d = new D(delegate(string s) { return s.Length == 1; });

IEnumerable<string> query = names.Where(d).Select...

?

最佳答案

因为它们是不同的类型。

给出相同类型错误的较短版本:

delegate bool D(string s);
delegate bool F(string s);

D d = new D(delegate(string s) { return s.Length == 1; });
F f = d;

Error 1 Cannot implicitly convert type 'Program.D' to 'Program.F'



以及扩展方法Where定义为
Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

所以你需要一个Func<string, bool>D相似但不兼容。

关于linq - 在 where 子句中委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10243458/

相关文章:

c# - 空检查扩展方法

c# - Action<T> 为变量赋值

mysql - 我需要在具有次要条件的 SQL 表中查找/替换值

plsql - 左连接返回的行数少于预期?

php - 在 MySQL PHP 中添加附加 where 子句

c# - 从 DbLinq 源代码创建 Linq to sqlite dbml

java - HQL 中的 Linq ".any"等价物

vb.net - LINQ 除了使用自定义比较器

swift - 如何在 Swift 中将变量传递回父级

ios - 尝试创建协议(protocol),获取时找不到协议(protocol)声明