LINQ (Language Integrated Query)

by mahidhar

LINQ provides a unified syntax for querying collections. It integrates querying capabilities directly into C#.

Example:

code
using System;
using System.Collections.Generic;
using System.Linq;

namespace NationalParks
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> parks = new List<string> { "Yellowstone", "Yosemite", "Zion", "Grand Canyon", "Great Smoky Mountains" };

            var query = from park in parks
                        where park.StartsWith("Y")
                        select park;

            foreach (var park in query)
            {
                Console.WriteLine(park);
            }
        }
    }
}

Advanced Use Case: LINQ with Dictionaries:

code
using System;
using System.Collections.Generic;
using System.Linq;

namespace NationalParks
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> parkEstablishments = new Dictionary<string, int>
            {
                { "Yellowstone", 1872 },
                { "Yosemite", 1890 },
                { "Grand Canyon", 1919 },
                { "Great Smoky Mountains", 1934 }
            };

            var query = from park in parkEstablishments
                        where park.Value > 1900
                        select park;

            foreach (var park in query)
            {
                Console.WriteLine($"{park.Key} was established in {park.Value}");
            }
        }
    }
}