Introduction
The with expression creates a new object with modified properties
Example 1
Add a new Product to a list, then use the CategoryId value when adding a second item to the list with the with expression.
Model
public record Product(int Id, string Name, int CategoryId)
{
public int Id { get; set; } = Id;
public string Name { get; set; } = Name;
public int CategoryId { get; set; } = CategoryId;
}
List<Product> products = [];
Product product = new(1, "Football", 2);
products.Add(product);
products.Add(product with { Id = 2, Name = "Golf" });
foreach (var (id, name, categoryId) in products)
{
Console.WriteLine($"{id,-3}: {name,-20}{categoryId}");
}
Example 2
An extension of Example 1 that uses a Dictionary to add data.
var (products, categories) = MockedData.GetProductsAndCategories();
Dictionary<int, string> dictionary = new()
{
[2] = "Golf",
[3] = "Formula 1 racing",
[4] = "Soccer"
};
Product product = new(1, "Football", 2);
products.Add(product);
foreach (var (key, value) in dictionary)
{
products.Add(product with { Id = key, Name = value });
}
var joined =
products.Join(
categories,
p => p.CategoryId,
c => c.Id,
(p, c) => new
{
ProductId = p.Id,
ProductName = p.Name,
CategoryName = c.Name
});
foreach (var item in joined)
{
Console.WriteLine($"{item.ProductId,-3}: {item.ProductName,-20}{item.CategoryName}");
}
Real life
Imagine a file service that reads files by file name, which determines the product category. This would be a good case for the with expression.


Top comments (0)