Enumerable.Concat<TSource> 方法

定義

串連兩個序列。

C#
public static System.Collections.Generic.IEnumerable<TSource> Concat<TSource> (this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second);

類型參數

TSource

輸入序列之項目的類型。

參數

first
IEnumerable<TSource>

要串連的第一個序列。

second
IEnumerable<TSource>

要串連到第一個序列的序列。

傳回

IEnumerable<TSource>

IEnumerable<T>,其中包含兩個輸入序列的串連項目。

例外狀況

firstsecondnull

範例

下列程式代碼範例示範如何使用 Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) 串連兩個序列。

C#
class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

static Pet[] GetCats()
{
    Pet[] cats = { new Pet { Name="Barley", Age=8 },
                   new Pet { Name="Boots", Age=4 },
                   new Pet { Name="Whiskers", Age=1 } };
    return cats;
}

static Pet[] GetDogs()
{
    Pet[] dogs = { new Pet { Name="Bounder", Age=3 },
                   new Pet { Name="Snoopy", Age=14 },
                   new Pet { Name="Fido", Age=9 } };
    return dogs;
}

public static void ConcatEx1()
{
    Pet[] cats = GetCats();
    Pet[] dogs = GetDogs();

    IEnumerable<string> query =
        cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));

    foreach (string name in query)
    {
        Console.WriteLine(name);
    }
}

// This code produces the following output:
//
// Barley
// Boots
// Whiskers
// Bounder
// Snoopy
// Fido

串連兩個序列的替代方式是建構集合,例如序列的數位,然後套用 SelectMany 方法,傳遞識別選取器函式。 下列範例示範這個 用法 SelectMany

C#
Pet[] cats = GetCats();
Pet[] dogs = GetDogs();

IEnumerable<string> query =
    new[] { cats.Select(cat => cat.Name), dogs.Select(dog => dog.Name) }
    .SelectMany(name => name);

foreach (string name in query)
{
    Console.WriteLine(name);
}

// This code produces the following output:
//
// Barley
// Boots
// Whiskers
// Bounder
// Snoopy
// Fido

備註

此方法是使用延後執行來實作。 立即傳回值是物件,可儲存執行動作所需的所有資訊。 除非直接在 GetEnumerator C# 或 Visual Basic 中使用 foreach 來列舉對象,否則 For Each 不會執行這個方法所表示的查詢。

方法 Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)Union 方法不同,因為 Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) 方法會傳回輸入序列中的所有原始專案。 方法 Union 只會傳回唯一的專案。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0