CSharp - Return lookup of different type from ToLookup operator

Introduction

For our elementSelector, we just concatenate the firstName and lastName members.

Using the elementSelector variation of the ToLookup operator can return a different data type in the Lookup than the input sequence element's data type.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from  w  w w .j  av  a  2 s.com*/
{
    static void Main(string[] args)
    {
        ILookup<int, string> lookup = Actor.GetActors()
          .ToLookup(k => k.birthYear,
                          a => string.Format("{0} {1}", a.firstName, a.lastName));

        //  Let's see if we can find the 'one' born in 1964.
        IEnumerable<string> actors = lookup[1964];
        foreach (var actor in actors)
            Console.WriteLine("{0}", actor);
    }
}
public class Actor
{
    public int birthYear;
    public string firstName;
    public string lastName;

    public static Actor[] GetActors()
    {
        Actor[] actors = new Actor[] {
           new Actor { birthYear = 1964, firstName = "Kotlin", lastName = "Ruby" },
           new Actor { birthYear = 1968, firstName = "Owen", lastName = "Windows" },
           new Actor { birthYear = 1960, firstName = "Javascript", lastName = "Spader" },
           new Actor { birthYear = 1964, firstName = "Scala", lastName = "Java" },
         };

        return (actors);
    }
}

Result

Related Topic