Updated April 3, 2023
Introduction to LINQ Group by
LINQ Group by used to group the list of collected items/data based on the particular value of the key and based on the grouping data it returns the result as the collection of elements of key and values as IGrouping<TKey, TElement>. The GroupBy method is the same as the SQL group by statement.
Syntax:
var _data = result.GroupBy(test=>test.getData);
By using the LINQ GroupBy() syntax we can group the data based on the particular value of the key.
How group by query works in LINQ?
In GroupBy method, it returns a collection that has a specific key and with the inner collection with a base of the key field value. The groupby used to grouping the collection of items in a specified group and returns the collection of elements based on several key values, each and every group is symbolized by IGrouping<TKey, TElement>, for example, the groupby returns IEnumerable<IGrouping<TKey,EmployeeDetails>> from the EmployeeDetails collection,
In GroupBy function, it returns an IEnumerable<IGrouping<TKey, TSource>> where TKey is nothing but the Key value on which the grouping has been formed and TSource is the collection of elements that matches the grouping key value.
Let’s see the following example programmatically,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LinqGroupBy
{
class Program
{
public class EmployeeDetails
{
public int employeeID
{
get;
set;
}
public string employeeName
{
get;
set;
}
public string employeeQualification
{
get;
set;
}
public int DepartmentID { get; set; }
public int empAge { get; set; }
public static List<EmployeeDetails> Get_Employees()
{
return new List<EmployeeDetails>(){
new EmployeeDetails() {employeeID = 1000, employeeName = "Henry",DepartmentID=1,
employeeQualification = "MCA", empAge=21},
new EmployeeDetails() {employeeID = 1005, employeeName = "Remo", DepartmentID=2,
employeeQualification = "B.E",empAge=23},
new EmployeeDetails() {employeeID = 1001, employeeName = "Smith",DepartmentID=1,
employeeQualification = "MCA",empAge=21},
new EmployeeDetails() {employeeID = 1007, employeeName = "Rio",DepartmentID=3,
employeeQualification = "B.E",empAge=27},
new EmployeeDetails() {employeeID = 1003, employeeName = "Jack",DepartmentID=1,
employeeQualification = "M.Sc",empAge=21},
new EmployeeDetails() {employeeID = 1004, employeeName = "Peter",DepartmentID=3,
employeeQualification = "B.E",empAge=27},
};
}
}
static void Main(string[] args)
{
Console.WriteLine("\tUsing Linq- Group By\n");
var _result = from e in EmployeeDetails.Get_Employees()
group e by e.empAge;
//each groups getting iterated
foreach (var get_age in _result)
{
Console.WriteLine("\nEmployees in the age Group of: {0}\n", get_age.Key); //every group had a individual keys
foreach (EmployeeDetails e in get_age)
Console.WriteLine("Employee Name: {0}", e.employeeName);
}
Console.ReadKey();
}
}
}
The above program displays the following result as the group of employees how having are in the same age groups, those employee names will be displayed in the same collection and each grouped collection has a key.
Examples
The group by used to group the collection of items in a specified group and returns the collection of elements based on several key values, let’s see the examples programmatically.
Example #1
Code:
using System;
using System.Collections.Generic;
using System. Linq;
namespace GroupBy_LinQ
{
class Program_1
{
public class UserData
{
public string userName { get; set; }
public int userAge { get; set; }
public string userPlace { get; set; }
}
static void Main(string[] args)
{
var getValues = new List<UserData>()
{
new UserData { userName = "Smith", userAge = 33, userPlace = "Singapore" },
new UserData { userName = "Rio", userAge = 40, userPlace = "Singapore" },
new UserData { userName = "Jack", userAge = 21, userPlace = "Malaysia" },
new UserData { userName = "Danial", userAge = 23, userPlace = "Singapore" },
new UserData { userName = "Peter", userAge = 15, userPlace = "Malaysia" },
};
var GroupBy_place = getValues.GroupBy(UserData => UserData.userPlace);
Console.WriteLine("\tUsing LINQ-GroupBy\n");
foreach(var group in GroupBy_place)
{
Console.WriteLine("\tUsers from " + group.Key + ":");
foreach(var res in group )
Console.WriteLine("\t- " + res.userName);
}
}
}
}
In the above program we getting the result based on the user locations, there are two locations by using groupby method we got two different results.
var GroupBy_place = getValues.GroupBy(UserData => UserData.userPlace);
by using the group.key it takes the value of property which grouped by the user location and it returns the collection of elements based on several key values,
{
Console.WriteLine("\tUsers from " + group.Key + ":");
foreach(var res in group )
Console.WriteLine("\t- " + res.userName);
}
In this above code, you can see the iteration process in the group using ‘foreach’ loop here each and every group is symbolized by IGrouping<TKey, TElement>, the output will be as follows,
Output:
Example #2
In this program we use the substring function based on the first letter of every user’s we can list the user details by using the LINQ groupby method, it lists the groups based on the first letters of the user’s name let’s see the following program ill desired output,
Code:
using System;
using System.Collections.Generic;
using System. Linq;
namespace GroupBy_LinQ
{
class Program_2
{
public class UserData
{
public string userName { get; set; }
public int userAge { get; set; }
public string userPlace { get; set; }
}
static void Main(string[] args)
{
var getValues = new List<UserData>()
{
new UserData { userName = "Smith", userAge = 33, userPlace = "Singapore" },
new UserData { userName = "Sije", userAge = 40, userPlace = "Singapore" },
new UserData { userName = "Henry", userAge = 21, userPlace = "Malaysia" },
new UserData { userName = "Harry", userAge = 21, userPlace = "Malaysia" },
new UserData { userName = "Paul", userAge = 23, userPlace = "Singapore" },
new UserData { userName = "Peter", userAge = 15, userPlace = "Malaysia" },
};
Console.WriteLine("\tUsing LINQ-GroupBy\n");
var usersGroupedByFirstLetters = getValues.GroupBy(user => user.userName.Substring(0, 1));
foreach(var group in usersGroupedByFirstLetters)
{
Console.WriteLine("Users starting with " + group.Key + ":");
foreach(var user in group)
Console.WriteLine("-" + user.userName);
}
}
}
}
In the above program, we called the function Substring () which is used to call the name, to obtain the beginning letter, and calling the function LINQ which is to develop the groups of usernames as our requirements. The result will be as follows,
Output:
Conclusion
In this article, we almost see the examples programmatically about GroupBy() method of LINQ explained programmatically using several examples, by using this LINQ GroupBy() method we can easily return a collection of elements as key and values.
Recommended Articles
This is a guide to LINQ Group by. Here we discuss Introduction, syntax, How group by query works in LINQ? examples with code implementation. You may also have a look at the following articles to learn more –