Group the names by first letter, but put results into a list of temporary Grouping objects. - CSharp LINQ

CSharp examples for LINQ:Group By

Description

Group the names by first letter, but put results into a list of temporary Grouping objects.

Demo Code



using System;// ww  w.j a  va  2s . c  om
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {

        string[] names = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
        var nameGroups = from n in names
                         group n by n[0] into tempGrp
                         where tempGrp.Key != 't' && tempGrp.Key != 'n'
                         select tempGrp; // Selecting the current temporary group, not n.
        foreach (var nameGroup in nameGroups)
        {
            Console.WriteLine("\tWords that begin with '{0}':", nameGroup.Key);
            foreach (var name in nameGroup)
            {
                Console.WriteLine("\t{0}", name);
            }
        }
    }
}

Result


Related Tutorials