LINQ in C#

Sagar Kumar
4 min readMar 1, 2023

LINQ (Language Integrated Query) is a feature in C# that allows developers to write queries to retrieve data from different data sources such as arrays, collections, and databases. LINQ is a powerful tool that simplifies the code and increases productivity.

Here’s an example of using LINQ in C# to retrieve data from an array:

using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Retrieve all the even numbers from the array
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
// Print the even numbers
foreach (var number in evenNumbers)
{
Console.WriteLine(number);
}
}
}

In this example, we have an array of integers called numbers. We want to retrieve all the even numbers from the array using LINQ.

We first use the from keyword to specify the range variable num, which represents each element in the array. Then, we use the where keyword to filter the even numbers by checking if num % 2 is equal to 0. Finally, we use the select keyword to project the even numbers from the array.

The result of the LINQ query is an IEnumerable<int> that contains the even numbers. We then use a foreach loop to iterate over the even numbers and print them to the console.

Output

2
4
6
8
10

This is just a simple example of how LINQ can be used in C# to retrieve data from an array. LINQ can also be used to retrieve data from other data sources such as collections and databases, and can perform complex queries that involve multiple conditions, joins, and groupings.

here’s an advanced example of using LINQ in C# to retrieve data from a collection of objects and perform some complex operations:

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// Create a collection of employee objects
List<Employee> employees = new List<Employee>
{
new Employee { Id = 1, Name = "John", Department = "Sales", Salary = 5000 },
new Employee { Id = 2, Name = "Mary", Department = "Marketing", Salary = 6000 },
new Employee { Id = 3, Name = "Bob", Department = "Sales", Salary = 4500 },
new Employee { Id = 4, Name = "Jane", Department = "IT", Salary = 7000 },
new Employee { Id = 5, Name = "Mike", Department = "IT", Salary = 8000 }
};
// Retrieve all the employees in the Sales department with a salary greater than 4000
var salesEmployees = from emp in employees
where emp.Department == "Sales" && emp.Salary > 4000
select emp;
// Print the names and salaries of the sales employees
Console.WriteLine("Sales Employees:");
foreach (var emp in salesEmployees)
{
Console.WriteLine($"Name: {emp.Name}, Salary: {emp.Salary:C}");
}
// Calculate the average salary of all employees
var avgSalary = employees.Average(emp => emp.Salary);
Console.WriteLine($"Average Salary: {avgSalary:C}");
// Group the employees by department and calculate the average salary for each department
var deptAvgSalary = from emp in employees
group emp by emp.Department into deptGroup
select new { Department = deptGroup.Key, AvgSalary = deptGroup.Average(emp => emp.Salary) };
// Print the department names and average salaries
Console.WriteLine("Department Average Salaries:");
foreach (var dept in deptAvgSalary)
{
Console.WriteLine($"Department: {dept.Department}, Avg Salary: {dept.AvgSalary:C}");
}
}
}
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public int Salary { get; set; }
}

In this example, we have a collection of Employee objects with properties such as Id, Name, Department, and Salary. We want to retrieve data from the collection using LINQ and perform some complex operations.

We first use LINQ to retrieve all the employees in the Sales department with a salary greater than 4000. We then use a foreach loop to iterate over the sales employees and print their names and salaries to the console.

We then use LINQ to calculate the average salary of all employees in the collection using the Average extension method. We store the result in the avgSalary variable and print it to the console.

Next, we use LINQ to group the employees by department using the group by clause. We then calculate the average salary for each department using the Average extension method. We store the result in an anonymous type that contains the department name and average salary, and print it to the console.

Output:

Sales Employees:
Name: John, Salary: $5000.00
Name: Bob, Salary: $4500.00
Department Average Salaries:
Department: Sales, Avg Salary: $4750.00
Department: Marketing, Avg Salary: $6000.00
Department:

--

--