我有一个关于 LINQ 中的棘手问题的问题(对我来说几乎是棘手的!)。
可以写出下面的linqQuery
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var linqQuery= digits.Where((digit, index) => digit.Length < index);
利用Enumerable.Where<TSource>(IEnumerable<TSource>, Func<TSource, Int32, Boolean>)
可枚举重载方法,使用查询语法
var linqQuery = from ...
where ...
select ...;
?
方法Enumerable.Where<TSource>(IEnumerable<TSource>, Func<TSource, Int32, Boolean>)
使用 Int32
参数作为源元素的索引,我想知道是否可以从查询语法而不是其他 Enumberable 重载方法中推断出此方法 Enumerable.Where<TSource> Method (IEnumerable<TSource>, Func<TSource, Boolean>)
.
这里是 MSDN 引用
最佳答案
不,这不可能。查询语法仅支持可用操作的一个子集。查询语法中的任何内容都不会编译成 Where
的重载。
您拥有的一切都很好。不过,这里有一些查询语法的想法,可以让您编写这样的操作:
var linqQuery = from d in digits.Where((digit, index) => digit.Length < index)
// You can do more stuff here if you like
select d;
还可以考虑首先投影到包含索引的类型(不幸的是,帮助您执行此操作的 Select
重载具有相同的问题),然后在查询中执行过滤器和其他下游操作-语法:
var linqQuery = from tuple in digits.Select((digit, index) =>
new { Digit = digit, Index = index })
where tuple.Digit.Length < tuple.Index
// You can do more stuff here if you like
select tuple.Digit;
同时考虑 moreLinq的 SmartEnumerable
,它使您免于投影到元组的麻烦:
var linqQuery = from tuple in digits.AsSmartEnumerable()
where tuple.Value.Length < tuple.Index
// You can do more stuff here if you like
select tuple.Value;
关于c# - LINQ 和 Enumerable.Where<TSource>(IEnumerable<TSource>, Func<TSource, Int32, Boolean>) 重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13902978/