簡體   English   中英

C#LINQ聚合將字符串轉換為int

[英]C# LINQ Aggregate converts string to int

我在CodeHunt.com上玩一個游戲,我根本無法理解為什么在以下代碼中,當分配的類型應該為IEnumerable <string時,VisualStudio / Codehunt編譯器希望Aggregate函數將字符串從字符串轉換回int >

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

首先,總是有兩個不同的步驟:

  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 ,而不是string列表。

但是,任何Aggregate函數僅根據列表中的元素對起作用。 因此,您的邏輯必須與當前編寫的邏輯大不相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM