LINQ Examples

In this blog, I will try to create samples of LINQ extension methods which are very helpful in accomplishing things which earlier would take 10-15 lines (or more) of code and were difficult to manage as well as to understand. I will also try to keep this blog as a running list of good LINQ extension methods.
First up, let's see the whole code listing. For my data, I have created a simple SportsPerson class and have populated with arbitrary values.
public class A07LinqExamples
    {
        public static void Run()
        {
            ToLookupExample();

            ToDictionaryExample();
        }

        private static void ToDictionaryExample()
        {
            Console.WriteLine("\n---------ToDictionaryExample-----------------");
            var sportsPersons = LoadSportsPerson();

            // get a dictionary with id as id and value as SportsPerson
            var sportsPersonDict = sportsPersons.ToDictionary(sp => sp.Id, sp => sp);

            // get sportsperson with id 8
            var val = sportsPersonDict[8];
            Console.WriteLine(val.Name + "(" + val.Sport + ")");
        }

        public static void ToLookupExample()
        {
            Console.WriteLine("\n---------ToLookupExample-----------------");
            var sportsPersons = LoadSportsPerson();

            // get a lookup with id as sport and value as list of SportsPerson
            var sportsPersonsCategorized = sportsPersons.ToLookup(sp => sp.Sport, sp => sp);

            // get all sportsperson who play cricket
            foreach (var lkup in sportsPersonsCategorized["Cricket"])
                Console.WriteLine(lkup.Name);
        }

        private static IEnumerable<SportsPerson> LoadSportsPerson()
        {
            return new List<SportsPerson>()
                       {
                           new SportsPerson() {Id = 1, Name = "Sachin Tendulkar", Sport = "Cricket"},
                           new SportsPerson() {Id = 10, Name = "Roger Federer", Sport = "Tennis"},
                           new SportsPerson() {Id = 8, Name = "Rafael Nadal", Sport = "Tennis"},
                           new SportsPerson() {Id = 6, Name = "Pete Sampras", Sport = "Tennis"},
                           new SportsPerson() {Id = 5, Name = "Andre Agassi", Sport = "Tennis"},
                           new SportsPerson() {Id = 4, Name = "Brian Lara", Sport = "Cricket"},
                           new SportsPerson() {Id = 7, Name = "Glenn McGrath", Sport = "Cricket"},
                           new SportsPerson() {Id = 3, Name = "Michael Jordan", Sport = "Basketball"},
                           new SportsPerson() {Id = 9, Name = "Magic Johnson", Sport = "Basketball"},
                           new SportsPerson() {Id = 2, Name = "Steve Nash", Sport = "Basketball"}
                       };
        }
    }

    public class SportsPerson
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Sport { get; set; }
    }
ToDictionary
ToDictionary creates a key-value pair from an IEnumerable where all the keys have to be unique. The inputs that you have to provide are obviously the key and the value.

ToLookup
Many a times there is a need to create a lookup structure with some kind of grouping. For example, in our case, we want all sports persons to be categorized based on the sports they play. Lookup provides a simple key-value pair approach where the key can be the sports category and value can be all the sportsperson that belong to that sport. This is very different than dictionary. In a dictionary the key has to be unique. In Lookup keys can be the same.

Result