A concatenation is a process in which one sequence is appended into another sequence. In LINQ, the Conact() method or operator serves the same purpose. It is used to append two same types of sequences or collections and return a new sequence or collection without removing the duplicates from the two sequences.
Following is the pictorial representation of the LINQ Conact() method.
Let's discuss the linq Conact() operator with examples.
Example 1. Concatenate two List of strings.
public class Program
{
public static void Main()
{
List<string> strList1 = new List<string>() {"Virat","Sachin","Dhoni" };
List<string> strList2 = new List<string>() { "Saurav", "Raina", "Yadav" };
var result = strList1.Concat(strList2);
foreach (string str in result)
{
Console.WriteLine(str);
}
Console.ReadLine();
}
}
Example 2. Concatenate EmployeeList with ContactList and display the result in console.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class Program
{
public static void Main()
{
List<Employee> employees = new List<Employee>()
{
new Employee(){ Id=1,Name="Sachin",Email="s@gmail.com"},
new Employee(){ Id=2,Name="Arjun",Email="a@gmail.com"},
new Employee(){ Id=3,Name="Vikash",Email="v@gmail.com"},
};
List<Contact> contacts = new List<Contact>()
{
new Contact(){ Id=4,Name="Nivi",Email="Ni@gmail.com"},
new Contact(){ Id=5,Name="Neha",Email="Ne@gmail.com"},
new Contact(){ Id=6,Name="Nikita",Email="Nik@gmail.com"},
};
var result = employees.Select(x => new { x.Id, x.Name, x.Email })
.Concat(contacts.Select(x => new {x.Id,x.Name,x.Email }));
foreach (var item in result)
{
Console.WriteLine("{0}:{1}:{2}",item.Id,item.Name,item.Email);
Console.WriteLine("------");
}
Console.ReadLine();
}
}
Output:
Please note that With complex type we use the projection (Select) operator along with Concat operator because concatenation of two lists is possible, if and only if two collections have an equal number and same type properties if you have 10 properties in a class and 5 properties in other class then for concatenating purpose you can project similar properties into an anonymous type to make collections eligible for concatenation.
This is how we can use LINQ Concat() method to combine multiple sequences into a single sequence.