"i"在这个LINQ语句中的价值在哪里?

won*_*rld 4 c# linq

我对这个选择LINQ语句的行为感到困惑.在LOOK HERE注释的下方,您可以看到选择的LINQ语句.该选择语句在employees集合上.因此,它应该只接受x作为输入参数.出于好奇,我传递i给代表,它的工作原理.当它遍历select时,它首先指定0然后再递增1.结果可以在本文末尾看到.

变量i从哪里获得价值?首先,为什么它允许我使用i范围内无处的变量.它不在本地Main方法中的全局范围内.任何帮助都是理解这个谜.

namespace ConsoleApplication
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Employee
    {
        public int EmployeedId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var employees = new List<Employee>()
                                {
                                    new Employee() { FirstName = "John", LastName = "Doe" }, 
                                    new Employee() { FirstName = "Jacob", LastName = "Doe" }
                                };

            // LOOK HERE...
            var newEmployees = employees.Select((x, i) => new { id = i, name = x.FirstName + " " + x.LastName });

            newEmployees.ToList().ForEach(x => { Console.Write(x.id); Console.Write(" "); Console.WriteLine(x.name); });

            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果是

在此输入图像描述

0 John Doe
1 Jacob Doe
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 5

Enumerable.Select有一个重载项,用于投射序列中元素的当前索引.此外Enumerable.WhereEnumerable.SkipWhile/ TakeWhile拥有它.你可以像for-loop中的循环变量一样使用它,这有时很方便.

使用索引创建匿名类型以将长列表分组为4的组的一个示例:

var list = Enumerable.Range(1, 1000).ToList();

List<List<int>> groupsOf4 = list
    .Select((num, index) => new { num, index })
    .GroupBy(x => x.index / 4).Select(g => g.Select(x => x.num).ToList())
    .ToList();  // 250 groups of 4
Run Code Online (Sandbox Code Playgroud)

或者Where只选择偶数索引的一个:

var evenIndices = list.Where((num, index) => index % 2 == 0);
Run Code Online (Sandbox Code Playgroud)

可能还很重要的是,您可以使用仅在方法语法中投影索引的这些重载.LINQ查询语法不支持它.