.NET Framework 4.0新增了兩個String.Concat的多載函式Concat(IEnumerable)、與Concat(IEnumerable)。

image_thumb.png

這兩個新的多載函式跟String.Join的新多載函式類似,能幫我們串連IEnumerable集合中的元素,不必預先將元素轉換為字串後再處理,同時也支援更多的集合類型。

完整範例如下:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] stringCollection = { "123", "456", "789" };
            int[] intCollection = { 123, 456, 789 };
            Object[] objCollection = { 123, "456", 789.0f };
            float[] floatCollection = { 123.0f, 456.0f, 789.0f };

            ShowValue<String>("stringCollection", stringCollection);
            ShowValue<int>("intCollection", intCollection);
            ShowValue<Object>("objCollection", objCollection);
            ShowValue<float>("floatCollection", floatCollection);
        }

        static void ShowValue<T>(string title, IEnumerable<T> values)
        {
            Console.WriteLine("{0}: {1}", title, string.Concat<T>(values));
        }
    }
}

運行結果如下:

image_thumb_1.png

  • String.Concat 方法