Find out the difference between Concat and Union in CSharp

Description

The following code shows how to find out the difference between Concat and Union.

Example


  //w w w  .j a  va2  s  .  co  m


using System;
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 }
        foreach (int item in concat)
            Console.WriteLine(item);
        
        IEnumerable<int> union = seq1.Union(seq2);     //  { 1, 2, 3, 4, 5 }
        foreach (int item in union)
            Console.WriteLine(item);        
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    LINQ »




Operator
Select
Where
OrderBy
Group
Join
Let
LINQ