C# Enumerable ToLookup(IEnumerable, Func, Func)

Description

Creates a Lookup from an IEnumerable according to specified key selector and element selector functions.

Syntax


public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
  this IEnumerable<TSource> source,
  Func<TSource, TKey> keySelector,
  Func<TSource, TElement> elementSelector
)/*from   w  w  w  .  j a va 2  s. com*/

Parameters

  • TSource - The type of the elements of source.
  • TKey - The type of the key returned by keySelector.
  • TElement - The type of the value returned by elementSelector.
  • source - The IEnumerable to create a Lookup from.
  • keySelector - A function to extract a key from each element.
  • elementSelector - A transform function to produce a result element value from each element.

Example

The following code example demonstrates how to use ToLookup to create a Lookup by using a key selector function and an element selector function.


/*from  ww w.ja v  a 2s  .c o m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  

    List<Package> packages =new List<Package>
            { new Package { Company = "A", Weight = 25.2, TrackingNumber = 8L },
              new Package { Company = "B", Weight = 18.7, TrackingNumber = 9L },
              new Package { Company = "C", Weight = 6.0, TrackingNumber = 2L },
              new Package { Company = "D", Weight = 9.3, TrackingNumber = 28L },
              new Package { Company = "E", Weight = 33.8, TrackingNumber = 3L } };
 
    ILookup<char, string> lookup = packages
        .ToLookup(p => Convert.ToChar(p.Company.Substring(0, 1)),
                  p => p.Company + " " + p.TrackingNumber);
 
    foreach (IGrouping<char, string> packageGroup in lookup)
    {
        Console.WriteLine(packageGroup.Key);
        foreach (string str in packageGroup)
            Console.WriteLine("    {0}", str);
    }
  }
}
    
class Package{
    public string Company { get; set; }
    public double Weight { get; set; }
    public long TrackingNumber { get; set; }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable