c# LINQ Aggregate将字符串转换为整型

本文关键字:转换 整型 字符串 LINQ Aggregate | 更新日期: 2023-09-27 18:17:11

我正在玩CodeHunt.com上的一个级别,我根本无法理解为什么在以下代码中,VisualStudio/Codehunt编译器希望聚合函数从字符串转换回int,当分配的类型应该是IEnumerable <字符串>

using System;
using System.Linq;
class Program {
    static void Main(string[] args) {
        Console.WriteLine(Puzzle(4)); //supposed to return "0____ 01___ 012__ 0123_ 01234 "
        Console.ReadLine();
    }
    public static string Puzzle(int n) {
        IEnumerable<int> enunums = Enumerable.Range(0, n);
        IEnumerable<string> enustrings = enunums.Aggregate((a, b) => a.ToString() + b.ToString() + new string('_', n - b) + " ");
        return string.Join("", enustrings);
    }
}

c# LINQ Aggregate将字符串转换为整型

首先,总是有两个不同的步骤:

  1. 调用函数并得到结果
  2. 尝试将结果赋值给变量

第一步甚至没有考虑左边的变量(在您的例子中是IEnumerable<string>)。它只查看函数的声明。

根据Aggregate函数的文档,声明是:

public static TSource Aggregate<TSource>(this IEnumerable<TSource> source,
                                         Func<TSource, TSource, TSource> func);

注意它在IEnumerable<TSource>中的部分。由于调用enunums.Aggregate, TSource被分配给int。由于这个TSource在任何地方都被使用,包括第二个函数参数和返回类型,它自然期望到处都是int,即最终形式返回一个简单的int

public static int Aggregate<int>(this IEnumerable<int> source,
                                 Func<int, int, int> func);

可以调用Aggregate的另一个重载,它接受另一种类型的种子输入,然后追加到它后面:

public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source,
                                                          TAccumulate seed,
                                                          Func<TAccumulate, TSource, TAccumulate> func);

转换成:

public static string Aggregate<int, string>(this IEnumerable<int> source,
                                            string seed,
                                            Func<string, int, string> func);

这应该返回最终结果string,而不是字符串列表。

然而,任何Aggregate函数都只适用于列表中的元素对。所以你的逻辑必须和现在写的有很大的不同。