CachedSelect
.CachedSelect<,>(selector, equalityComparer?) is similar to .Select<,>, however it caches values and returns same value reference on every iteration.
// Car id source
List<string> keys = new List<string> { "XYZ-123", "ABC-789" };
// Car enumerable (constructs cars from id)
IEnumerable<Car> cars = keys.CachedSelect<string, Car>(id => new Car { Id = id });
// Get reference to first car
Car car0 = cars.First();
// Print cars
foreach (Car car in cars)
Console.WriteLine(car);
// Car { Id = XYZ-123, Name = }
// Car { Id = ABC-789, Name = }
// Remove second car
keys.RemoveAt(1);
// Print cars
foreach (Car car in cars)
Console.WriteLine(car);
// Car { Id = XYZ-123, Name = }
// Get reference to first car
Car car0x = cars.First();
// Enumerable still returns same reference
Console.WriteLine(object.ReferenceEquals(car0, car0x)); // True
// Dispose cache
((IDisposable)cars).Dispose();
// Disposed ABC-789
// Disposed XYZ-123
public record Car : IDisposable
{
public string Id { get; set; } = "id";
public string Name { get; set; } = "";
public void Dispose() => Console.WriteLine($"Disposed {Id}");
}
Full Example
Full example
using System;
using System.Collections.Generic;
using System.Linq;
using Avalanche.Utilities;
public class cachedselect
{
public static void Run()
{
{
// <01>
// Car id source
List<string> keys = new List<string> { "XYZ-123", "ABC-789" };
// Car enumerable (constructs cars from id)
IEnumerable<Car> cars = keys.CachedSelect<string, Car>(id => new Car { Id = id });
// Get reference to first car
Car car0 = cars.First();
// Print cars
foreach (Car car in cars)
Console.WriteLine(car);
// Car { Id = XYZ-123, Name = }
// Car { Id = ABC-789, Name = }
// Remove second car
keys.RemoveAt(1);
// Print cars
foreach (Car car in cars)
Console.WriteLine(car);
// Car { Id = XYZ-123, Name = }
// Get reference to first car
Car car0x = cars.First();
// Enumerable still returns same reference
Console.WriteLine(object.ReferenceEquals(car0, car0x)); // True
// Dispose cache
((IDisposable)cars).Dispose();
// Disposed ABC-789
// Disposed XYZ-123
// </01>
}
}
// <05>
public record Car : IDisposable
{
public string Id { get; set; } = "id";
public string Name { get; set; } = "";
public void Dispose() => Console.WriteLine($"Disposed {Id}");
}
// </05>
}