System.Linq Namespace
Namespace: System
Assembly: System.Linq.dll
Provides classes and interfaces that support programmers in implementing Language-Integrated Query (LINQ).
Classes
-
Enumerable
Provides a set of static extension methods for LINQ that allow you to create queries against objects that implement
IEnumerable<T>
.public static class Enumerable
-
Queryable
Provides a set of static extension methods for LINQ that allow you to create queries against objects that implement
IQueryable<T>
.public static class Queryable
Interfaces
-
IOrderedEnumerable<TElement>
Represents an ordered sequence of elements.
public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>, IEnumerable
-
IGrouping<TKey,TElement>
Represents a group of elements that have a common key.
public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable
Common LINQ Operations
The System.Linq
namespace enables powerful data querying capabilities in .NET. Some of the most common operations include:
- Filtering: Using methods like
Where()
to select elements that satisfy a condition. - Projection: Using methods like
Select()
to transform elements into a new form. - Ordering: Using methods like
OrderBy()
andOrderByDescending()
to sort elements. - Grouping: Using methods like
GroupBy()
to group elements by a key. - Joining: Using methods like
Join()
andGroupJoin()
to combine elements from different sequences. - Aggregation: Using methods like
Count()
,Sum()
,Average()
,Min()
, andMax()
to compute aggregate values.
Example: Filtering and Selecting
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 class Example
{
public static void Main(string[] args)
{
List<Product> products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 1200.00m },
new Product { Id = 2, Name = "Mouse", Price = 25.50m },
new Product { Id = 3, Name = "Keyboard", Price = 75.00m },
new Product { Id = 4, Name = "Monitor", Price = 300.00m }
};
// Get names of products with a price greater than 100.00
var expensiveProductNames = products
.Where(p => p.Price > 100.00m)
.Select(p => p.Name);
Console.WriteLine("Expensive Product Names:");
foreach (var name in expensiveProductNames)
{
Console.WriteLine(name);
}
}
}