Using the Grouping operator
The GroupBy clause is used to group the query in LINQ based on a common key.



Now, we add the Default.aspx page and write the following code:

  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <center> 
    <div>
        <h1>Using the Grouping operator</h1>
        <asp:ListBox ID="lbDetail" runat="server" Height="350px" Width="500px"></asp:ListBox> <br /> <br />
        <asp:Button ID="btnDisplayRecord" runat="server" Text="Display Record" Font-Bold="true" OnClick="btnDisplayRecord_Click" />
    
    </div>
            </center>
    </form>
</body>
</html>




Now, double click on Display Record button and write the following code:-

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnDisplayRecord_Click(object sender, EventArgs e)
    {
        lbDetail.Items.Clear();

        string[] words = { "ajay", "santosh", "apple", "banana", "pineapple", "apricot", "pooja kumari", "aarti", "blueberry", "cheery", "black", "papaya", "suneeta", "asmita"};

        var query = from w in words group w by w[0] into g select new { FirstLetter = g.Key, words = g };

        foreach (var g in query)
        {
            lbDetail.Items.Add("Word that starts from letter:- " + g.FirstLetter.ToString());
            foreach (var w in g.words)
            {
                lbDetail.Items.Add(w);
            }
        }
       
    }
}



Now run the application and click on Display Record button and get output.