Grouping Operators in LINQ



The operators put data into some groups based on a common shared attribute.

Operator Description C# Query Expression Syntax VB Query Expression Syntax
GroupBy Organize a sequence of items in groups and return them as an IEnumerable collection of type IGrouping<key, element> group … by -or- group … by … into … Group … By … Into …
ToLookup Execute a grouping operation in which a sequence of key pairs are returned Not Applicable Not Applicable

Example of GroupBy - Query Expression

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         List<int> numbers = new List<int>() { 35, 44, 200, 84, 3987, 4, 199, 329, 446, 208 };

         IEnumerable<IGrouping<int, int>> query = from number in numbers 
		                              group number by number % 2;    

         foreach (var group in query) {
            Console.WriteLine(group.Key == 0 ? "\nEven numbers:" : "\nOdd numbers:");
           
            foreach (int i in group)
               Console.WriteLine(i);
         }
			
         Console.ReadLine();                
      }
   }
}

VB

Module Module1
   Sub Main()
      Dim numbers As New System.Collections.Generic.List(Of Integer)(
      New Integer() {35, 44, 200, 84, 3987, 4, 199, 329, 446, 208})

      Dim query = From number In numbers 
                  Group By Remainder = (number Mod 2) Into Group
     
      For Each group In query
         Console.WriteLine(If(group.Remainder = 0, vbCrLf &"Even numbers:", vbCrLf &"Odd numbers:"))
		 
         For Each num In group.Group           
            Console.WriteLine(num)
         Next 
		 
      Next
	  
      Console.ReadLine()
	  
   End Sub
   
End Module

When the above code in C# or VB is compiled and executed, it produces the following result −

Odd numbers: 
35 
3987 
199 
329 

Even numbers: 
44 
200 
84 
4 
446 
208
linq_query_operators.htm
Advertisements