ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ForEachRef

Performs the specified action on each ValueType in the List<T> without copying it.

Source

static class Extensions {

    public delegate void RefAction<T>(ref T value) where T : struct;

    public static void ForEachRef<T>(this List<T> list, RefAction<T> action) where T : struct {
        if (list is null) throw new ArgumentNullException(nameof(list));
        if (action is null) throw new ArgumentNullException(nameof(action));
        var span = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(list);
        foreach (ref T item in span) {
            action(ref item);
        }
    }
}

Example

var l = new List<PointStruct>() {
    new PointStruct(1, 10),
    new PointStruct(2, 20),
    new PointStruct(3, 30),
};

var a = l.ToArray();

l.ForEachRef(static (ref PointStruct p) => p.Swap());

foreach (var p in l) {
    Console.WriteLine(p);
}

struct PointStruct {

    public int X, Y; 

    public PointStruct(int x, int y) {
        X = x;
        Y = y;
    }

    public void Swap() => this = new PointStruct(Y, X);

    public double Dist => Math.Sqrt((X * X) + (Y * Y));

    public override string ToString() => $"({X.ToString()},{Y.ToString()})";
}

Author: Fons Sonnemans

Submitted on: 8 dec. 2021

Language: csharp

Type: System.Collections.Generic.List<T>

Views: 2897