Open In App

C# Program to Split a String Collections into Groups

Given a collection of strings and you are required to split them into groups using C#. The standard query operator contains GroupBy grouping operator using which we can split a collection of strings easily. The working of the GroupBy operator is similar to the SQL GroupBy clause. It is used to return the group of elements that share the common attributes or keys from the given sequence or collection. 

Syntax:



Grouping<TKey, TElement> object.

Example:



Input: [“Java”, “Python”, “Swift”, “CSS”, “C#”, “Django”]

Output: Splitting the string collection into groups of two elements

               [“Java”, “Python”]

               [“Swift”, “CSS”]

               [“C#”, “Django”]

Input: [“Delhi”, “Goa”, “Chennai”, “Pune”, “Mumbai”, “Himachal”, “Kolkata”]

Output: Splitting the string collection into groups of three elements

               [“Delhi”, “Goa”, “Chennai”]

               [“Pune”, “Mumbai”, “Himachal”]

               [“Kolkata”]

Example:




// C# program to illustrate how to split a string 
// collections into groups 
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG{
  
static public void Main()
{
      
    // Initializing a an array of strings 
    string[] subjects = { "Java", "Python", "Swift", "CSS",
                          "C#", "Django", "C++", "Javascript"
                          "HTML", "PHP" };
  
      // Displaying the collection
    Console.Write("The subjects are: \n");
    Console.WriteLine(string.Join(", ", subjects));
  
      
      // Now splitting the string collection into
      // a group of three elements
    var subjectSplit = from i in Enumerable.Range(0, subjects.Length) 
                       group subjects[i] by i / 3;
                         
    Console.WriteLine("\nThe group of subjects are:");
    foreach(var subject in subjectSplit)
        subjectView(string.Join(",  ", subject.ToArray()));
}
  
// Print each group elements
static void subjectView(string subject)
{
    Console.WriteLine(subject);
}
}

Output:

The subjects are: 
Java, Python, Swift, CSS, C#, Django, C++, Javascript, HTML, PHP

The group of subjects are:
Java,  Python,  Swift
CSS,  C#,  Django
C++,  Javascript,  HTML
PHP

Explanation: In the above C# program with the help of subjects[] array(of string type) variable we are reading different subjects. Now we split the given subject[] collection into the group of three subjects using the groupby operator. To iterate over the collection, we are using for each statement but cannot be used to add or remove items from the source collection to avoid undefined results. Now display the given string which is divided into groups.


Article Tags :