开发者

Linq expression with multiple input parameters

I wrote the following code and I'm not able to understand how it is executed.

class Program
{
    static void Main(string[] args)
    {
        int[] nums = { 1, 5, 10, 3, 554, 34};
        var nn = nums.TakeWhile((n, junk) => n > junk);
        nn.Count();
        foreach (var a in nn)
        {
            Console.WriteLine(a);
        }
        Console.ReadKey();
    }
}

First I wrote the TakeWhile exp开发者_StackOverflow社区ression as n => n > 5. I'm able to understand that. But I just added one more parameter junk. What is junk here? What value is assigned to it during query exeution? How is it giving the output as 1, 5 and 10.


junk is the index of of the currently processed element - see http://msdn.microsoft.com/en-us/library/bb548775.aspx

Much more readable and understable would be

var nn = nums.TakeWhile((n, index) => n > index);


junk is the index. So what you're iterating over is:

(1, 0)  => true
(5, 1)  => true
(10, 2) => true
(3, 3)  => false => abort

The method signature you're using is:

public static IEnumerable<TSource> TakeWhile<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, int, bool> predicate
)

predicate
Type: System.Func(Of TSource, Int32, Boolean) A function to test each source element for a condition; the second parameter of the function represents the index of the source element.

http://msdn.microsoft.com/en-us/library/bb548775.aspx


Try using the "correct" names: var nn = nums.TakeWhile((n, index) => n > index); and it will be clear!

From the TakeWhile page: predicate Type: System.Func<TSource, Int32, Boolean> A function to test each source element for a condition; the second parameter of the function represents the index of the source element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜