Select operator

            1. What is the Select operator?

            2. What are the signatures of the Select operators?

            3. How to use the Select operator to give an index for an item in a collection?

The Select operator is used to project the result of a query making them available through the object that implements IEnumerable<T>.

 

            var italians = from c in Data.Customers

                           select new { c.Name, c.City };

 

There are two versions of the Select operator:

 

public static IEnumerable<TResult> Select<TSource, TResult>(

    this IEnumerable<TSource> source,

    Func<TSource, TResult> selector);

 

public static IEnumerable<TResult> Select<TSource, TResult>(

    this IEnumerable<TSource> source,

    Func<TSource, int, TResult> selector);

 

To give an index for an item in a collection we can use second version of the Select operator.

 

Example 2:

 

            var italiansIndexed = Data.Customers.

                                Select((c, selectIndex) => new { selectIndex, c.Name, c.City }).

                                Where(c => c.selectIndex > 1);

 

            foreach (var item in italiansIndexed)

            {

                Trace.WriteLine(item.ToString());

            }

 

Output:

 

{ selectIndex = 2, Name = James, City = Dallas }

{ selectIndex = 3, Name = Frank, City = Seattle }

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 )

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