[LINQ Operators] Concat

The “Concat” operator concatenates two sequences.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “Concat” operator

  • Deferred operator
  • Purpose: Concatenation

 

3. Prototypes

public static IEnumerable<T> Concat<T>
  (this IEnumerable<T> source, IEnumerable<T> sequence)

The “Concat()” operator concatenates a specified sequence to a source sequence.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var newEmps = emps.Where(e => e.Name.Contains("King"))
    .Concat(emps.Where(e => e.Name.Contains("Baker")));

foreach (var e in newEmps)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

 

5. Example 2 (Query Expression)

There’s no direct  translation to a query expression. But you can use the “Concat()” operator with a query expression.

var emps = Employee.GetEmployees();

var newEmps
  = (from e in emps
     where (e.Name.Contains("King"))
     select e)
    .Concat
    (from e in emps
     where (e.Name.Contains("Baker"))
     select e);
foreach (var e in newEmps)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s