代码之家  ›  专栏  ›  技术社区  ›  Kellen Stuart Alan

林克(x,i)是做什么的?

  •  1
  • Kellen Stuart Alan  · 技术社区  · 5 年前

    今天我无意中发现了这段代码,意识到我根本不懂它。

    someArray.Select((x, i) => new XElement("entry",
                                new XElement("field", new XAttribute("name", "Option"), i + 1)
    

    有什么意义 (x, i) ? 我看到有人提到 i ,但我不明白 x 符合这个lamda的表达。

    一个整数?我看到最后有一个 i + 1

    谢谢你的帮助

    2 回复  |  直到 5 年前
        1
  •  4
  •   Phillip Ngan    5 年前

    这个 x 是价值,和 i 是索引。

    例如,代码片段:

    void Main()
    {
        var values = new List<int> {100, 200, 300};
        foreach( var v in values.Select((x, i) => (x, i))) // x is the value, i is the index
            Console.WriteLine(v);
    }
    

    (100,0)(200,1)(300,2)

    微软 documentation is here

        2
  •  3
  •   Davi    5 年前

    i . 另一个过载 Select ,其中 Function 传递的对象只接受一个参数,只访问元素(名为 x 在那个例子中)。

    这是 a link 选择

        3
  •  0
  •   timur    5 年前

    你看到的是 LINQ .Select() i 只是一个( 零基* x 按顺序。

    回到您的特定代码片段,它完全忽略了 和用途 基于一个 )最终转换为XML节点的值。所以如果你说

    var someArray = Enumerable.Range(9999,5); // I'm just generating some big numbers here, you can do the same with strings or objects - it doesn't matter.
    

    <entry>
      <field name="Option">1</field>
    </entry>
    
    <entry>
      <field name="Option">2</field>
    </entry>
    
    <entry>
      <field name="Option">3</field>
    </entry>
    
    <entry>
      <field name="Option">4</field>
    </entry>
    
    <entry>
      <field name="Option">5</field>
    </entry>