Linq查询中的意外结果始终为+ 1

Bas*_*ili 7 c# linq

我有以下代码,我期待不同的结果.
我已经例外的是以下的结果:100,110,120,200,500

  using System;
  using System.Collections.Generic;
  using System.Linq;

  namespace ConsoleApplication11
  {
    public class Program
    {
      static void Main(string[] args)
      {
        var values = new List<int> { 100, 110, 120, 200 , 500 };

        //  In my mind the result shall be like (100,0) => 100 + 0 = 100 
        //  In my mind the result shall be like (110,0) => 110 + 0 = 110 etc. 
        var sumLinqFunction = new Func<int, int, int>((x, y) => x + y);
        var outputs = values.Select(sumLinqFunction);

        foreach (var o in outputs)
          Console.WriteLine(o);
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

控制台输出(实际结果)

100
111
122
203
504
Run Code Online (Sandbox Code Playgroud)

我现在想知道从哪来来的+1?

Efr*_*isi 17

这是因为您正在使用的Select()方法重载的第二个参数只是输入集中项的索引.

编辑:

正如@ user7116建议的那样,您可能只想在投影函数中包含来自外部范围的值:

int y = 0;
var results = values.Select(x => x + y);
Run Code Online (Sandbox Code Playgroud)

  • @BassamAlugili在那个重载中没什么"神奇",它只是将项目索引传递给投影函数. (4认同)
  • @BassamAlugili:所以基本上你想要为列表中的所有值添加0.你为什么不把它原样留下?顺便说一句,"MAGIC OVERLOAD"非常有用.像`for-loop`一样有用. (2认同)

Hab*_*bib 7

你的Func,sumLinqFunction期待两个参数,添加它们然后返回它们的结果.

当您在Select语句中使用它时,它就像:

var outputs = values.Select((x, y) => x + y);
Run Code Online (Sandbox Code Playgroud)

它使用Select的重载,它希望第二个参数是索引.

selector的第一个参数表示要处理的元素. selector的第二个参数表示源序列中该元素的从零开始的索引.例如,如果元素按已知顺序并且您希望对特定索引处的元素执行某些操作,则此操作非常有用.如果要检索一个或多个元素的索引,它也很有用.

所以y从一开始0.每次迭代时,index(y)都会移动到下一个元素,因此您可以看到增量+1.

为了解释多一点,你可以修改Func显示的当前值xy这样的:

var sumLinqFunction = new Func<int, int, int>((x, y) =>
    {
        Console.WriteLine("x: {0} , y: {1}", x, y);
        return x + y;
    });
var outputs = values.Select(sumLinqFunction).ToList(); //iterate to get the results.
Run Code Online (Sandbox Code Playgroud)

这会给你:

x: 100 , y: 0
x: 110 , y: 1
x: 120 , y: 2
x: 200 , y: 3
x: 500 , y: 4
Run Code Online (Sandbox Code Playgroud)

对于你的评论:

我需要使用默认值0而不是索引来调用select!

然后,而不是Func你可以简单地做:

int y = 0;
var outputs = values.Select(r => r + y);
Run Code Online (Sandbox Code Playgroud)