0

where条款如何运作?

(digit, index) => digit.Length < index

代码

public void Linq5() 
    { 
        string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 

        var shortDigits = digits.Where((digit, index) => digit.Length < index); 

        Console.WriteLine("Short digits:"); 
        foreach (var d in shortDigits) 
        { 
            Console.WriteLine("The word {0} is shorter than its value.", d); 
        } 
    }

来源

编辑澄清 根据 Iswanto San

(digit, index) => digit.Length < index

变量声明:

(digit, index) -- digit as array of digits 

条件(如where中的子句SQL):

digit.Length < index

如果我错了,正确吗?如果我走对了,那么角色是什么=>

4

3 回答 3

2

这将返回列表中的所有元素,该元素Length低于该列表中的位置。

MSDN:Enumerable.Where<TSource> Method (IEnumerable<TSource>, Func<TSource, Int32, Boolean>)

predicate 的第一个参数表示要测试的元素。第二个参数表示源中元素的从零开始的索引。

它应该返回这些元素:

{ "five", "six", "seven", "eight", "nine" }
于 2013-03-16T07:07:51.427 回答
2

它选择长度小于它在数组中的索引的字符串。

于 2013-03-16T07:08:34.177 回答
1

这:

(digit, index) => digit.Length < index

digit将引用数组内容(在这种情况下digits),数据类型是String. index将引用数组索引,数据类型为int.

因此,该条件将输出长度小于其索引(位置)的数组内容。

例如:

digits="zero", index=0=> 假,长度=4,索引=0

digits="one", index=1=> 假,长度=3,索引=1

digits="two", index=2=> 假,长度=3,索引=2

digits="three", index=3=> 假,长度=5,索引=3

digits="four", index=4=> 假,长度=4,索引=4

digits="five", index=5=> 真,长度=4,索引=5

更多:Enumerable.Where

于 2013-03-16T07:09:45.287 回答