C#

Examples of Query Operations using LINQ in C#

Programmingempire

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 the 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.


Further Reading

Selection Sort in C#

Insertion Sort in C#

Bubble Sort in C#

How to Create Instance Variables and Class Variables in Python

Comparing Rows of Two Tables with ADO.NET

Example of Label and Textbox Control in ASP.NET

One Dimensional and Two Dimensuonal Indexers in C#

Private and Static Constructors in C#

Methods of Array Class

Anonymous Functions in C#

Programs to Find Armstrong Numbers in C#

Matrix Multiplication in C#

One Dimensional and Two Dimensional Indexers in C#

Static Class Example in C#

Rotating an Array in C#

Generic IList Interface and its Implementation in C#

Recursive Binary search in C#

C# Practice Questions

Creating Navigation Window Application Using WPF in C#

Find Intersection Using Arrays

An array of Objects and Object Initializer

Performing Set Operations in LINQ

Using Quantifiers in LINQ

Data Binding Using BulletedList Control

Grouping Queries in LINQ

Generic Binary Search in C#

Understanding the Quantifiers in LINQ

Join Operation using LINQ

Deferred Query Execution and Immediate Query Execution in LINQ

Examples of Query Operations using LINQ in C#

An array of Objects and Object Initializer

Language-Integrated Query (LINQ) in C#

How Data Binding Works in WPF

Examples of Connected and Disconnected Approach in ADO.NET

New Features in C# 9

IEnumerable and IEnumerator Interfaces

KeyValuePair and its Applications

C# Root Class – Object

Access Modifiers in C#

Learning Properties in C#

Learning All Class Members in C#

Examples of Extension Methods in C#

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

Understanding the Concept of Nested Classes in C#

LINQ To SQL Examples

A Beginner’s Tutorial on WPF in C#

Explaining C# Records with Examples

Everything about Tuples in C# and When to Use?

Creating Jagged Arrays in C#

Linear Search and Binary search in C#

Learning Indexers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Basic Examples

IEqualityComparer Interface

programmingempire

You may also like...