英語で読む

次の方法で共有


Enumerable.Concat<TSource> メソッド

定義

2 つのシーケンスを連結します。

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>

2 つの入力シーケンスの連結された要素が格納されている IEnumerable<T>

例外

first または secondnull です。

次のコード例では、 を使用 Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) して 2 つのシーケンスを連結する方法を示します。

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

2 つのシーケンスを連結するもう 1 つの方法は、シーケンスの配列などのコレクションを構築し、 メソッドを SelectMany 適用して ID セレクター関数を渡すことです。 この の使用例を次に 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# For Each または Visual Basic で を使用foreachして列挙されるまで実行されません。

メソッドは 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