LINQ in Practice · Lesson 3

Projecting records

Transform each item into the shape the next step needs.

How it works

Select applies a projection to every requested source element. Here it converts an order into an anonymous value with an identifier and a computed total. The original orders remain unchanged, and the projection exposes only the fields needed for printing. This is a useful boundary between a broad domain object and a small report row. Keep formatting near the display boundary so later calculations can still work with numeric values.

A projection can allocate a new object per element, so the shape and the number of enumerations affect costs even when the expression reads like a compact description.

Add a quantity field to the projected row and keep the original order intact. Try filtering before and after projection and compare which fields each predicate can access.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var orders = new[] { new Order("A", 3, 4m), new Order("B", 2, 5m) };
var rows = orders.Select(x => new { x.Id, Total = x.Count * x.Price });
foreach (var row in rows) Console.WriteLine($"{row.Id}:{row.Total}");
record Order(string Id, int Count, decimal Price);

Expected output

A:12
B:10
Try this
Project numbers as numbers until the display step.