Open In App

C# Program to Divide Sequence into Groups using LINQ

Improve
Improve
Like Article
Like
Save
Share
Report

Given a sequence, now our task is to divide the given sequence into groups using LINQ. So to this task first we generate a sequence then we select the elements from the given sequence and then group them together. 

Approach:

1. In C#, we can use LINQ by including the “System.Linq” namespace in our program.

2. Generate a sequence using Enumerable.Range(start, end) method,

public static System.Collections.Generic.IEnumerable<int> Range (int start, int count);

3. Now, we can select each element of the sequence and divide them by 20 and then group them after converting them into new forms.

var groups = from a in sequence.Select((p, q) => new { p, groups = q / 20 })
             group a.p by a.groups into b
             select new { Min = b.Min(), Max = b.Max() };

Example: In this program, firstly, In the first iteration, we have generated a sequence of numbers starting from 100 and ending at 100 + 100. Also, using the Select property we are dividing each element of the sequence by 20. Now, in the second iteration, we have converted these elements into new forms and grouped them using group property. The result is transformed into an enumerable collection of anonymous objects with a property Min and Max.

C#




// C# program to divide a sequence into
// groups using LINQ
using System;
using System.Linq;
using System.IO;
  
class GFG{
  
static public void Main()
{
      
    // Generating a sequence
    var sequence = Enumerable.Range(100, 100).Select(a => a / 20f);
      
    // Dividing the given sequence into groups
    var groups = from a in sequence.Select((p, q) => new { p, groups = q / 20 })
                 group a.p by a.groups into b
                 select new { Min = b.Min(), Max = b.Max() };
      
    // Displaying the results           
    foreach(var grps in groups)
        Console.WriteLine("Min: " + grps.Min + " Max:" + grps.Max);
}
}


Output

Min: 5 Max:5.95
Min: 6 Max:6.95
Min: 7 Max:7.95
Min: 8 Max:8.95
Min: 9 Max:9.95

Last Updated : 26 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads