.NET Core Documentation

LINQ to Objects Samples

LINQ to Objects Samples

Explore various samples demonstrating the power and versatility of Language Integrated Query (LINQ) with collections of objects in .NET Core.

Filtering Data (Where)

Learn how to filter collections based on specific criteria using the Where extension method.


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

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
}

public class Sample1
{
    public static void Main(string[] args)
    {
        var products = new List
        {
            new Product { Id = 1, Name = "Laptop", Price = 1200.00m, CategoryId = 1 },
            new Product { Id = 2, Name = "Keyboard", Price = 75.00m, CategoryId = 1 },
            new Product { Id = 3, Name = "Mouse", Price = 25.00m, CategoryId = 1 },
            new Product { Id = 4, Name = "Monitor", Price = 300.00m, CategoryId = 2 },
            new Product { Id = 5, Name = "Webcam", Price = 50.00m, CategoryId = 2 }
        };

        // Select products with a price greater than 100
        var expensiveProducts = products.Where(p => p.Price > 100.00m);

        Console.WriteLine("Expensive Products:");
        foreach (var product in expensiveProducts)
        {
            Console.WriteLine($"- {product.Name} (${product.Price})");
        }
    }
}
                
Expected Output:
Expensive Products:
- Laptop ($1200.00)
- Monitor ($300.00)

Sorting Data (OrderBy, OrderByDescending)

Discover how to sort collections in ascending or descending order using OrderBy and OrderByDescending.


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

public class Product // Assuming Product class is defined as above
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
}

public class Sample2
{
    public static void Main(string[] args)
    {
        var products = new List
        {
            new Product { Id = 1, Name = "Laptop", Price = 1200.00m, CategoryId = 1 },
            new Product { Id = 2, Name = "Keyboard", Price = 75.00m, CategoryId = 1 },
            new Product { Id = 3, Name = "Mouse", Price = 25.00m, CategoryId = 1 },
            new Product { Id = 4, Name = "Monitor", Price = 300.00m, CategoryId = 2 },
            new Product { Id = 5, Name = "Webcam", Price = 50.00m, CategoryId = 2 }
        };

        // Sort products by price in descending order
        var sortedProducts = products.OrderByDescending(p => p.Price);

        Console.WriteLine("Products Sorted by Price (Descending):");
        foreach (var product in sortedProducts)
        {
            Console.WriteLine($"- {product.Name} (${product.Price})");
        }
    }
}
                
Expected Output:
Products Sorted by Price (Descending):
- Laptop ($1200.00)
- Monitor ($300.00)
- Keyboard ($75.00)
- Webcam ($50.00)
- Mouse ($25.00)

Grouping Data (GroupBy)

Learn to group elements in a collection based on a specified key using GroupBy.


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

public class Product // Assuming Product class is defined as above
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
}

public class Sample3
{
    public static void Main(string[] args)
    {
        var products = new List
        {
            new Product { Id = 1, Name = "Laptop", Price = 1200.00m, CategoryId = 1 },
            new Product { Id = 2, Name = "Keyboard", Price = 75.00m, CategoryId = 1 },
            new Product { Id = 3, Name = "Mouse", Price = 25.00m, CategoryId = 1 },
            new Product { Id = 4, Name = "Monitor", Price = 300.00m, CategoryId = 2 },
            new Product { Id = 5, Name = "Webcam", Price = 50.00m, CategoryId = 2 }
        };

        // Group products by CategoryId
        var productsByCategory = products.GroupBy(p => p.CategoryId);

        Console.WriteLine("Products Grouped by Category:");
        foreach (var categoryGroup in productsByCategory)
        {
            Console.WriteLine($"Category ID: {categoryGroup.Key}");
            foreach (var product in categoryGroup)
            {
                Console.WriteLine($"- {product.Name} (${product.Price})");
            }
        }
    }
}
                
Expected Output:
Products Grouped by Category:
Category ID: 1
- Laptop ($1200.00)
- Keyboard ($75.00)
- Mouse ($25.00)
Category ID: 2
- Monitor ($300.00)
- Webcam ($50.00)

Projections (Select)

Transform elements from one type to another using the Select extension method.


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

public class Product // Assuming Product class is defined as above
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
}

public class Sample4
{
    public static void Main(string[] args)
    {
        var products = new List
        {
            new Product { Id = 1, Name = "Laptop", Price = 1200.00m, CategoryId = 1 },
            new Product { Id = 2, Name = "Keyboard", Price = 75.00m, CategoryId = 1 },
            new Product { Id = 3, Name = "Mouse", Price = 25.00m, CategoryId = 1 }
        };

        // Create an anonymous type with just the product name and price
        var productInfo = products.Select(p => new { p.Name, p.Price });

        Console.WriteLine("Product Names and Prices:");
        foreach (var item in productInfo)
        {
            Console.WriteLine($"- {item.Name}: ${item.Price}");
        }
    }
}
                
Expected Output:
Product Names and Prices:
- Laptop: $1200.00
- Keyboard: $75.00
- Mouse: $25.00

Set Operations (Distinct, Union, Intersect, Except)

Perform set operations on collections like finding unique elements, combining, finding common, or differing elements.


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

public class Sample5
{
    public static void Main(string[] args)
    {
        var numbers1 = new List { 1, 2, 3, 4, 5, 5 };
        var numbers2 = new List { 4, 5, 6, 7, 8 };

        // Distinct elements from numbers1
        var distinctNumbers = numbers1.Distinct();
        Console.WriteLine("Distinct Numbers from List 1: " + string.Join(", ", distinctNumbers)); // Output: 1, 2, 3, 4, 5

        // Union of numbers1 and numbers2
        var unionNumbers = numbers1.Union(numbers2);
        Console.WriteLine("Union of List 1 and List 2: " + string.Join(", ", unionNumbers)); // Output: 1, 2, 3, 4, 5, 6, 7, 8

        // Intersect of numbers1 and numbers2
        var intersectNumbers = numbers1.Intersect(numbers2);
        Console.WriteLine("Intersection of List 1 and List 2: " + string.Join(", ", intersectNumbers)); // Output: 4, 5

        // Except of numbers1 from numbers2 (elements in numbers2 not in numbers1)
        var exceptNumbers = numbers2.Except(numbers1);
        Console.WriteLine("Elements in List 2 not in List 1: " + string.Join(", ", exceptNumbers)); // Output: 6, 7, 8
    }
}
                
Expected Output:
Distinct Numbers from List 1: 1, 2, 3, 4, 5
Union of List 1 and List 2: 1, 2, 3, 4, 5, 6, 7, 8
Intersection of List 1 and List 2: 4, 5
Elements in List 2 not in List 1: 6, 7, 8