c# - Linq 查询中的意外结果总是 + 1

标签 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);
      }
    }
  }

控制台输出(真实结果)

100
111
122
203
504

我现在想知道这个 +1 是从哪里来的?

最佳答案

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

编辑:

正如@user7116 所建议的,您可能只想在投影函数中包含一个来自外部作用域的值:

int y = 0;
var results = values.Select(x => x + y);

关于c# - Linq 查询中的意外结果总是 + 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18852397/

相关文章:

asp.net - LINQ:不支持查询运算符 'ElementAtOrDefault'

c# - 128位整数的指南

C#:映射 IDataReader.GetTableSchema() 和 DbType 枚举?

c# - C#Linq帮助提高性能吗?

c# - LINQ,创建集合的唯一集合

c# - 动态创建 Func<T,TR> C#

c# - 读取 Excel 工作表时,如果列的值为数字,则数据表中返回 null

c# - 注册通用工厂

c# - "Red X of Doom"在WinForm中绘制多个时间序列图表

c# - 如何将 bool 转换为可为 null 的 bool(bool?)