【问题标题】:C# LINQ Aggregate converts string to intC# LINQ Aggregate 将字符串转换为 int
【发布时间】:2014-08-09 15:33:22
【问题描述】:

我在 CodeHunt.com 上玩关卡,但我无法理解为什么在下面的代码中,VisualStudio/Codehunt 编译器希望 Aggregate 函数在分配的类型应该是时从字符串转换回 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 type-conversion aggregate


【解决方案1】:

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

  1. 调用函数并获取结果
  2. 尝试将结果分配给变量

第一步甚至不考虑左侧变量(在您的情况下,IEnumerable&lt;string&gt;)。它只查看函数的声明。

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

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

注意它接收IEnumerable&lt;TSource&gt; 的部分。因为您调用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 函数只能根据列表中的元素对起作用。因此,您的逻辑必须与当前编写的逻辑大不相同。

【讨论】:

  • 部分评论未发布
  • 好的,var enustring = enunums.Aggregate("", (total, next) => total.ToString() + next.ToString() + new string('', n -下一个)+“”); // 返回 "0____ 1__ 2__ 3_ " 但我应该能够解决这个问题。谢谢
猜你喜欢
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多