Concat

In this chapter you will learn:

  1. How to use Concat operator
  2. Concatenate one array to another
  3. Concat vs Union
  4. Take then concatenate

Using Concat operator

Concat adds all the elements of the first and second sequence.

using System;//from j a  va 2s.c  o  m
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] seq1 = { 1, 2, 3 };
        int[] seq2 = { 3, 4, 5 };

        IEnumerable<int> concat = seq1.Concat(seq2);

        foreach(int i in concat){
            Console.WriteLine(i);
        }
    }
}

The output:

Concatenate one array to another

using System;//from   j  a v  a 2 s . com
using System.Linq;


public class MainClass{

   public static void Main(string[] args){   
         String[] First = { "One", "Two", "Three" };
         String[] Second = { "Four", "Five", "Six" };

         var ThisQuery = First.Concat<String>(Second);

         foreach (String ThisElement in ThisQuery)
            Console.WriteLine(ThisElement);


   }
}

Concat vs Union

using System;//from   j  av  a 2  s.  c  o m
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {

        int[] seq1 = { 1, 2, 3 };
        int[] seq2 = { 3, 4, 5 };
        IEnumerable<int> concat = seq1.Concat(seq2);    //  { 1, 2, 3, 3, 4, 5 }
        IEnumerable<int> union = seq1.Union(seq2);     //  { 1, 2, 3, 4, 5 }
    }
}

Take then concatenate

using System;/* j  a v  a  2s. co m*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"ant", "arding", "arrison", "eyes", "over", "java2s.com"};
        IEnumerable<string> items = presidents.Take(5).Concat(presidents.Skip(5));

        foreach (string item in items)
            Console.WriteLine(item);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Use Contains operator
  2. Contains with string value
  3. Contains with string value and IEqualityComparer
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip