SelectMany operator

            1. What is the SelectMany operator?

            2. Why do we need the SelectMany operator?

            3. What are the signatures of the SelectMany operators?

            4. How to use the SelectMany operator to get a partial data from the inner

            sequence?

The SelectMany operator performs a one-to-many element projection over a sequence.

 

Example 1:

            var grouppedOrders = from c in Data.Customers

                           select c.Orders;

 

Output:

OperatorsData.Order[]

OperatorsData.Order[]

OperatorsData.Order[]

OperatorsData.Order[]

 

 

Sometimes we need to get a flattened sequence. To achieve this goal we can use followed LINQ syntax:

 

Example 2:

            var flattenedOrders = from c in Data.Customers

                                    from o in c.Orders

                                    select o;

 

Which is actually transformed by C# compiler into:

 

            var flattenedOrders = Data.Customers.

                                    SelectMany(c => c.Orders);

 

So, every time when we use an inner from operator it is transformed into the SelectMany method.

 

There are four versions of the SelectMany operator:

 

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

    this IEnumerable<TSource> source,

    Func<TSource, IEnumerable<TResult>> selector);

 

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

    this IEnumerable<TSource> source,

    Func<TSource, int, IEnumerable<TResult>> selector);

 

public static IEnumerable<TResult> SelectMany<TOuter, TInner, TResult>(

    this IEnumerable<TOuter> source,

    Func<TOuter, IEnumerable<TInner>> selector,

    Func<TOuter, TInner, TResult> resultSelector);

 

public static IEnumerable<TResult> SelectMany<TOuter, TInner, TResult>(

    this IEnumerable<TOuter> source,

    Func<TOuter, int, IEnumerable<TInner>> selector,

    Func<TOuter, TInner, TResult> resultSelector);

 

To get a partial data from a sequence we can use the followed syntax:

 

Example 3:

 

            var flattenedPartialOrders = from c in Data.Customers

                                            from o in c.Orders

                                            select new { o.IdProduct, o.Shipped};

 

Output:

 

{ IdProduct = 1, Shipped = False }

{ IdProduct = 2, Shipped = True }

{ IdProduct = 1, Shipped = False }

{ IdProduct = 3, Shipped = True }

{ IdProduct = 3, Shipped = True }

{ IdProduct = 5, Shipped = False }

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