1

I have the following code

    IEnumerable<int> numbers = 
        Enumerable.Range(1, 5)
        .Reverse();
    Func<int, string> outputFormat = x => x + "...";
    IEnumerable<string> countdown = numbers.Select(outputFormat);
    foreach (string s in countdown)
    {
        Console.WriteLine(s);
    }

Is there a way to "eliminate" foreach loop from the code, something like

Console.Write(countdown.EnumerateOverItems())

without actually writing custom method (e.g. using LINQ or delegates somehow)?

4

3 に答える 3

2

次のコードを使用できます。

Console.WriteLine(string.Join(Environment.NewLine, countdown));

古いバージョンの .NET では、string.Joinその takeのオーバーロードはなくIEnumerable<T>、 のみであることに注意してくださいstring[]。この場合、次のようなものが必要です。

Console.WriteLine(string.Join(Environment.NewLine, countdown.ToArray()));

完全を期すために、コレクションに要素が含まれていない場合はstring、次のようにすることができます。

Console.WriteLine(string.Join(Environment.NewLine, countdown.Select(v => v.ToString()).ToArray()));
于 2014-08-08T12:36:39.847 に答える