GroupBy operator

            1. What is the GroupBy operator?

            2. What are the signatures of the GroupBy operators?

            3. What does happening when we use the GroupBy operators?

The GroupBy operator allows grouping the elements of a sequence.

There are four versions of the GroupBy operator:

 

public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource,

TKey>(

    this IEnumerable<TSource> source,

    Func<TSource, TKey> keySelector);

 

public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource,

TKey>(

    this IEnumerable<TSource> source,

    Func<TSource, TKey> keySelector,

    IEqualityComparer<TKey> comparer);

 

public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource,

TKey, TElement>(

    this IEnumerable<TSource> source,

    Func<TSource, TKey> keySelector,

    Func<TSource, TElement> elementSelector);

 

public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource,

TKey, TElement>(

    this IEnumerable<TSource> source,

    Func<TSource, TKey> keySelector,

    Func<TSource, TElement> elementSelector,

    IEqualityComparer<TKey> comparer);

 

public interface IGrouping<TKey, TElement> : IEnumerable<TElement>

{

    TKey Key { get; }

}

 

Example 1:

            var expr = from c in Data.Customers

                        group c by c.Country;

 

            foreach (IGrouping<Countries, Customer> key in expr)

            {

                Trace.WriteLine("Country: " + key.Key);

                foreach (Customer item in key)

                {

                    Trace.WriteLine("Customer name: " + item.Name);

                }

            }

Output:

 

Country: Italy

Customer name: Paolo

Customer name: Marco

 

Country: USA

Customer name: James

Customer name: Frank

Customer name: Frank

 

 

This is actually transformed by C# compiler into:

 

IEnumerable<IGrouping<Countries, Customer>> expr = Data.Customers.GroupBy(c => c.Country);

 

When we use the GroupBy operators it groups the source sequence by the key which is defined by function, it also allows us to map element from the source sequence into the result sequence using elementSelector function. After grouping the GroupBy operator yields the resulting groups within IGrouping interface. The overloaded versions of the GroupBy operator allow passing the custom comparers. By default the GroupBy operator use the EqualityComparer.

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