LINQ Grouping operator in ASP.NET


The Grouping operators in LINQ are used to put data into groups so that the elements in each group share a common attribute. The Group clause is the Grouping operator used in LINQ. The Group clause returns a sequence of IGrouping<TKey, TElement> objects that contain zero or more items that match the key value for the group.
The syntax of using the GroupBy clause is:
 For C#
public static IEnumerable<IGrouping<K, T>> GroupBy<T, K>( Me IEnumerable<T> source, Function<T, K> keySeIector)

Lets take an simple example

        <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="Grouping Operator Linq" />

Code behind code

protected void Button1_Click(object sender, EventArgs e)
        string[] fruits = { "apple", "banana", "pineapple", "papaya", "blueberry", "cheery" };
        var groupword = from w in fruits
                        group w by w[0] into g
                        select new { FirstLetter = g.Key, fruits = g };
        foreach (var g in groupword)
          ListBox1 .Items .Add ("Words that start from letter:"+g.FirstLetter .ToString());
            foreach (var w in g.fruits)
ListBox1 .Items .Add (w);

code generate the following output

LINQ Grouping operator in ASP.NET

According to above given example. Grouping index start from 0. Here we take two for-each loop first one for printing message with starting letter of English such as 'a' and second one for printing grouping letter words like 'a' for apple and 'p' for "pineapple" and "papaya". 


Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites