ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Immutable Record Transformation with LINQ

C#

Goal -- WPM

Ready
Exercise Algorithm Area
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public record Product(int Id, string Name, decimal Price, int StockQuantity);
6public record ProductSummary(int ProductId, string ProductName, string PriceDescription);
7
8public static class ProductTransformer
9{
10public static IEnumerable<ProductSummary> CreateSummaries(IEnumerable<Product> products)
11{
12if (products == null)
13{
14throw new ArgumentNullException(nameof(products));
15}
16
17return products.Select(p => new ProductSummary(
18ProductId: p.Id,
19ProductName: p.Name.ToUpper(),
20PriceDescription: p.Price > 100m ? "Premium" : "Standard"
21));
22}
23}
Algorithm description viewbox

Immutable Record Transformation with LINQ

Algorithm description:

This C# code defines two immutable records, `Product` and `ProductSummary`, and a static method `CreateSummaries` that transforms a collection of `Product` objects into `ProductSummary` objects. It uses LINQ's `Select` method to project each `Product` into a new `ProductSummary`, demonstrating how to create new immutable data structures from existing ones without modifying the originals. This is a common pattern for data transformation and reporting.

Algorithm explanation:

The `CreateSummaries` method takes an `IEnumerable<Product>` and returns an `IEnumerable<ProductSummary>`. It first checks if the input collection is null. The core transformation is achieved using LINQ's `Select` extension method. For each `Product` object `p` in the input collection, a new `ProductSummary` object is created. The `ProductId` is directly mapped from `p.Id`. The `ProductName` is derived by converting `p.Name` to uppercase. The `PriceDescription` is determined by a conditional logic: if `p.Price` is greater than 100, it's categorized as "Premium"; otherwise, it's "Standard". Since `Product` and `ProductSummary` are immutable records, the original `Product` objects are never modified. The `Select` method returns an `IEnumerable<ProductSummary>`, which is lazily evaluated. The time complexity is O(N), where N is the number of products, as each product is processed once. The space complexity is O(N) if the resulting `IEnumerable` is materialized into a list or array, otherwise O(1) for the iterator itself.

Pseudocode:

Record Product(Id, Name, Price, StockQuantity)
Record ProductSummary(ProductId, ProductName, PriceDescription)

Function CreateSummaries(products):
  If products is null, throw ArgumentNullException.
  For each product in products:
    Create a new ProductSummary:
      ProductId = product.Id
      ProductName = product.Name converted to uppercase
      PriceDescription = "Premium" if product.Price > 100, else "Standard"
  Return the collection of new ProductSummaries.