C#

Examples of Query Operations using LINQ in C#

In this post, I will demonstrate several Examples of Query Operations using LINQ in C#. In order to get an overview of LINQ, you can read this article on Language-Integrated Query (LINQ) in C#.

Examples of Query Operations using LINQ in C#

Since LINQ helps us in creating queries that work with various kinds of data sources, we will use arrays for representing the data sources. In order to learn queries on SQL Server database, read this article on LINQ To SQL Examples.

Selection

Basically, the Selection operation returns the data. Further, this operation returns the whole data as well as the subset of data. Even more, it can also return the computed values. As an illustration, see following examples.

Example 1

The following example shows how a selection operation is used to fetch values from an array of integers. Additionally, the query also returns the computed values.

using System;
using System.Linq;
namespace QueryOperations
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Data Source: ");
            int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
            foreach (int i in arr)
                Console.Write(i + " ");
            Console.WriteLine();
            Console.WriteLine("Examples of Selection...");
            var q1 = from p in arr
                     select (p, p + 1, p * p, p * p * p);
            foreach(var ob in q1)
            {
                Console.WriteLine($"Item1: {ob.p}, Item2: {ob.Item2}, Item3: {ob.Item3}, Item4: {ob.Item4}");
            }
        }
    }
}

Output

Examples of Query Operations using LINQ in C#
Examples of Query Operations using LINQ in C#

Example 2

In a similar manner, we can also use an array of objects. The following example shows how an array of objects of the Employee class acts as the data source for the query. Furthermore, the query also returns a computed value called Increment.

class Employee
    {
        public String ename { get; set; }
        public int salary { get; set; }
        public override string ToString()
        {
            return $"Employee Name: {ename}, Salary: {salary}";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee[] arr1 = new Employee[]
            {
                new Employee{ename="A", salary=24000},
                new Employee{ename="B", salary=59000},
                new Employee{ename="C", salary=44000},
                new Employee{ename="D", salary=73000}
           };
            Console.WriteLine("Data Source: ");
            foreach (Employee ob in arr1)
                Console.WriteLine(ob + " ");
            Console.WriteLine();
            Console.WriteLine("After Executing Selection Query: ");

            var q2 = from p in arr1
                     select new { p.ename, p.salary, Increment = p.salary * 0.2 };
            foreach (var ob in q2)
            {
                Console.WriteLine($"Name: {ob.ename}, Salary: {ob.salary}, Increment: {ob.Increment}");
            }
        }
    }

Output

Selection Query on an Object Array as the Data Source
Selection Query on an Object Array as the Data Source

Sorting

The following examples illustrate sorting in LINQ.

Example 3

As shown in the next query, LINQ performs sorting using the orderby clause. Also, you can sort in descending order with the use of orderby …. descending clause.

Console.WriteLine("Examples of Sorting...");
            var q3 = from p in arr
                     orderby p descending
                     select (p, p * p);
            foreach (var ob in q3)
            {
                Console.WriteLine($"Item1: {ob.p}, Item2: {ob.Item2}");
            }

            var q4 = from p in arr1
                     orderby p.salary
                     select new { p.ename, p.salary, Increment = p.salary * 0.2 };
            foreach (var ob in q4)
            {
                Console.WriteLine($"Name: {ob.ename}, Salary: {ob.salary}, Increment: {ob.Increment}");
            }

Output

Sorting using the orderby Clause
Sorting using the orderby Clause

Filtering

Certainly, many times we need to retrieve data that satisfies certain criteria. Therefore, we need filtering. The following examples demonstrate filtering using the where clause.

Example 4

The following examples show the usage of where clause for filtering.

 Console.WriteLine("Examples of Filtering...");
            Console.WriteLine("Elements with values > 4");
            var q5 = from p in arr
                     where p>4
                     select (p, p * p);
            foreach (var ob in q5)
            {
                Console.WriteLine($"Item1: {ob.p}, Item2: {ob.Item2}");
            }
            Console.WriteLine("Employee Records where increment > 10000");
            var q6 = from p in arr1
                     where p.salary*0.2>10000
                     select new { p.ename, p.salary, Increment = p.salary * 0.2 };
            foreach (var ob in q6)
            {
                Console.WriteLine($"Name: {ob.ename}, Salary: {ob.salary}, Increment: {ob.Increment}");
            }

Output

Filtering using the where Clause
Filtering using the where Clause

Summary

In this article on Examples of Query Operations using LINQ in C#, the query operations on Selection, Sorting, and Filtering are covered. Furthermore, the examples also demonstrate the use of LINQ to Objects. In other words, the queries mentioned here operate on IEnumerable<T> collection.

Further examples on Join and Grouping queries are given here.


Related Topics

A Beginner’s Tutorial on WPF in C#

Everything about Tuples in C# and When to Use?

Linear Search and Binary Search in C#

Creating Jagged Arrays in C#

Learning Indexers in C#

Understanding Method Parameter Modifiers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Practice Questions

C# Basic Examples

Private and Static Constructors in C#

Constructors in C#

C# Arrays

C# Examples

How to Create a C# Console Application

Creating Navigation Window Application Using WPF in C#

LINQ To SQL Examples

Understanding the Concept of Nested Classes in C#

How to Setup a Connection with SQL Server Database in Visual Studio

Examples of Extension Methods in C#

Learning All Class Members in C#

Access Modifiers in C#

C# Root Class – Object

KeyValuePair and its Applications

IEnumerable and IEnumerator Interfaces

IEqualityComparer Interface

New Features in C# 9

Generic IList Interface and its Implementation in C#

Examples of Connected and Disconnected Approach in ADO.NET

How Data Binding Works in WPF

Language-Integrated Query (LINQ) in C#

Leave a Reply

Your email address will not be published. Required fields are marked *