Basics of LINQ in C#

Introduction

LINQ is nothing but a language-integrated query language. This helps developers query data from various data sources like XML, collections, and databases, among others. The following are the key features of LINQ:

Query Expressions: We can write code very similar to SQL language to query data. This makes it easy to read code and filter data in a familiar way.

Standard Query Operators: Standard query operators like the WHERE clause, GROUP BY, ORDER BY, and JOIN are supported.

LINQ to Objects: We can query in-memory objects like arrays, lists, and dictionaries using LINQ.

LINQ to SQL: LINQ can be used to query relational databases. We can write strongly typed queries, which means that these queries are checked for correctness at compile time rather than runtime. The framework converts the query into actual SQL statements so that it can be executed in the database.

LINQ to XML: We can query XML using LINQ. For example, we can loop through each repeating record in XML and check for duplicates in any field. You can count the number of occurrences of a particular repeating record, and so on.

LINQ Provider: It serves as an intermediary between LINQ and the data source.

Example Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace POCLinqConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creates a list of integers and initializes the list with a collection of ten integers
            var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            //Uses LINQ query to query even numbers.
            //from num in numbers -- This means it is iterating over each number in the list
            //where num % 2 == 0: This is a filter condition. It filters even numbers
            //selects even numbers in the list
            var evenNumbers = from num in numbers
                              where num % 2 == 0
                              select num;
            //It iterates over the list of even numbers
            foreach(var number in evenNumbers)
            {
                Console.WriteLine(number);
            }

        }
    }
}


Output:


Comments

Popular posts from this blog

Exploring the Compilation of a C# Program

Difference between static members and instance members

Enforcing Uniqueness in Multiple Fields of a Database Table