```html LINQ to Objects Samples – .NET Framework 3.5

LINQ to Objects Samples

Filtering (Where)

Retrieve all numbers greater than 5 from an array.


int[] numbers = { 1, 3, 5, 7, 9, 11 };
var result = numbers.Where(n => n > 5);
foreach (var n in result)
    Console.WriteLine(n);
            

Projection (Select)

Project a list of objects to a new anonymous type.


var people = new[] {
    new { Name = "Alice", Age = 30 },
    new { Name = "Bob", Age = 25 }
};
var names = people.Select(p => p.Name);
foreach (var name in names)
    Console.WriteLine(name);
            

Ordering (OrderBy, ThenBy)

Sort a list of products first by category then by price.


var products = new[] {
    new { Name = "Pen", Category = "Stationery", Price = 1.20m },
    new { Name = "Laptop", Category = "Electronics", Price = 899.99m },
    new { Name = "Notebook", Category = "Stationery", Price = 2.50m }
};
var sorted = products
    .OrderBy(p => p.Category)
    .ThenBy(p => p.Price);
foreach (var p in sorted)
    Console.WriteLine($"{p.Category} - {p.Name} : ${p.Price}");
            

Grouping (GroupBy)

Group words by their first letter.


string[] words = { "apple", "apricot", "banana", "blueberry", "cherry" };
var groups = words.GroupBy(w => w[0]);
foreach (var g in groups)
{
    Console.WriteLine($"Letter {g.Key}:");
    foreach (var w in g) Console.WriteLine($"  {w}");
}
            

Joining (Join)

Join two collections on a common key.


var customers = new[] {
    new { Id = 1, Name = "Alice" },
    new { Id = 2, Name = "Bob" }
};
var orders = new[] {
    new { CustomerId = 1, Total = 120.0 },
    new { CustomerId = 2, Total = 75.5 },
    new { CustomerId = 1, Total = 30.0 }
};
var query = customers.Join(
    orders,
    c => c.Id,
    o => o.CustomerId,
    (c, o) => new { c.Name, o.Total });
foreach (var item in query)
    Console.WriteLine($"{item.Name} ordered ${item.Total}");
            

Aggregation (Count, Sum, Average)

Calculate aggregate values from a numeric collection.


int[] scores = { 85, 92, 78, 90, 88 };
int count = scores.Count();
int sum = scores.Sum();
double avg = scores.Average();
Console.WriteLine($"Count: {count}, Sum: {sum}, Average: {avg:F2}");
            
```