[LINQ Operators] Select

The “Select” operator performs a projection over a sequence. You need to provide a selector (lambda expression) as an argument.

 

1. Sample Data Object

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

 

2. “Select” operator

  • Deferred operator
  • Purpose: Projection

 

3. Prototypes

public static IEnumerable Select<TSource, TResult>(
  this IEnumerable<TSource> source,
  Func<TSource, TResult> selector);

public static IEnumerable Select<TSource, TResult>(
  this IEnumerable<TSource> source,
  Func<TSource, int, TResult> selector); // index

The “Select()” operator creates a new type as a return sequence. The second prototype has an integer input argument; which is an index number (zero-based) for the element from the input sequence.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var newEmps = emps.Select(e => new
  { EmployeeName = $"{e.Id}: {e.Name}" });

foreach (var e in newEmps)
{
  Console.WriteLine(e.EmployeeName);
}

 

5. Example 2 (Query Expression)

var emps = Employee.GetEmployees();

var newEmps
  = from e in emps
    select new { EmployeeName = $"{e.Id}: {e.Name}" };

foreach (var e in newEmps)
{
  Console.WriteLine(e.EmployeeName);
}

 

6. Example 3 (Standard Operator): with an index number

var emps = Employee.GetEmployees();

var newEmps = emps.Select((e,i) => new
  { Index= i, EmployeeName = e.Name });

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

 

7. Example 4 (Query Expression): with an index number

There is no direct translation to a query expression.

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