1

我有一个关于 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>)Enumerable 重载方法,使用查询语法

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 参考

没有 Int32 参数的 Enumerable.Where 方法

带有 Int32 参数的 Enumerable.Where 方法

4

2 回答 2

3

不,这是不可能的。查询语法仅支持可用操作的子集。查询语法中的任何内容都不会编译为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;

还要考虑moreLinqSmartEnumerable,它可以省去投影到元组的麻烦:

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;
于 2012-12-16T16:06:38.727 回答
1

不,没有办法使用查询语法调用该重载Where()(或类似重载)。Select()

从 C# 4.0 规范的第 7.16.2.4 节:

带有where子句的查询表达式

from x in e
where f
…

被翻译成

from x in ( e ) . Where ( x => f )
…
于 2012-12-16T16:00:33.247 回答