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.
- This supports query syntax in both the languages, C#, and VB.Net languages.
- GroupBy can also be used in the C# query. The into keyword allows you to continue with the query and can perform more query operations. Or in other words, it is a temporary identifier that allows you to perform additional query operations.
- A group with GroupBy can also be used in VB.Net.
- LINQ query is terminated with the Select or Groupby clause.
Grouping<TKey, TElement> object.
Input: [“Java”, “Python”, “Swift”, “CSS”, “C#”, “Django”]
Output: Splitting the string collection into groups of two elements
Input: [“Delhi”, “Goa”, “Chennai”, “Pune”, “Mumbai”, “Himachal”, “Kolkata”]
Output: Splitting the string collection into groups of three elements
[“Delhi”, “Goa”, “Chennai”]
[“Pune”, “Mumbai”, “Himachal”]
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.