Language Integrated Query (LINQ)

Lesson 6: Language Integrated Query (LINQ)

In this lesson, you will learn about Language Integrated Query (LINQ), a powerful feature that lets you query data in a consistent way across collections, databases, XML, and more.


🔍 What is LINQ?

LINQ allows you to write queries directly in C# or VB.NET, using familiar syntax to manipulate:

  • In-memory collections (LINQ to Objects).
  • Databases (LINQ to SQL, Entity Framework).
  • XML (LINQ to XML).

📝 Basic LINQ Query

Here is an example querying an array of integers:


using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6 };

        var evenNumbers = from n in numbers
                          where n % 2 == 0
                          select n;

        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
    }
}


⚙️ Extension Methods Syntax

You can also use method syntax with extension methods:


using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] words = { "apple", "banana", "cherry" };

        var filtered = words.Where(w => w.Contains("a"))
                            .OrderBy(w => w);

        foreach (var word in filtered)
        {
            Console.WriteLine(word);
        }
    }
}


📚 Common LINQ Methods

Here are some frequently used LINQ methods:

  • Where: Filter elements.
  • Select: Project elements into new forms.
  • OrderBy, OrderByDescending: Sorting.
  • First, FirstOrDefault: Get single elements.
  • Any, All: Test conditions.
  • Count: Count elements.

🌟 Benefits of LINQ

LINQ provides:

  • Type safety at compile time.
  • IntelliSense support in IDEs.
  • Consistent query patterns.
  • Readable, declarative code.

💡 Example: LINQ to XML

Reading elements from XML:


using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string xml = @"
                          
                          
                       ";

        XElement root = XElement.Parse(xml);

        var names = from f in root.Elements("fruit")
                    select f.Attribute("name").Value;

        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}


📝 Summary

LINQ is a powerful feature that unifies data querying across different sources with clear, concise syntax.


✅ Next Lesson

Lesson 7: Introduction to ASP.NET Core

تعليقات

المشاركات الشائعة من هذه المدونة

Entity Framework - ما هو ORM؟ ونبذة عن Dapper وNHibernate

1.1 SQL Introduction

Entity Framework - مقدمة عن Entity Framework