Apply operations in a one-dimensional array of instances on the same line using LINQ

Consider the following structures:

internal struct Coordinate
{
    public Double Top { get; set; }
    public Double Left { get; set; }
}

internal struct Dimension
{
    public Double Height { get; set; }
    public Double Width { get; set; }
}

internal struct Property
{
    public Boolean Visible { get; set; }
    internal String Label { get; set; }
    public String Value { get; set; }
    internal Coordinate Position { get; set; }
    public Dimension Dimensions { get; set; }
}

I need to manipulate 20 instances of Property. I would like to make it as clean as possible ... Is it possible to apply several operations to the Property array in one line of code?

I think something like:

new []
{
    InstanceOfProperty,
    InstanceOfProperty,
    InstanceOfProperty ...
}.Each(p => p.Dimensions.Height = 100.0);
+3
source share
3 answers

I ended up with this:

new List<Property> { InstanceOfProperty, InstanceOfProperty, ... }.ForEach((p =>
{
    p.Dimensions.Height = 0.0;
}));


Note. I converted structures to classes. If I went with the original structural design; I would have to “update” the structures in order to change their value. For instance:

new List<Property> { InstanceOfProperty, InstanceOfProperty, ... }.ForEach((p =>
{
    p.Dimensions = new Dimension { Height = 0.0 };
}));
0
source

If you wrote your own method Eachwith a delegate Action<T>, you could.

Edit:

. . , class?

Dimension Property , .

+1

Each, , IEnumerable<T>. , , ref:

public static class ExtensionMethods
{
    public delegate void RefAction<T>(ref T arg);

    public static void Each<T>(this T[] array, RefAction<T> action)
    {
        for(int i = 0; i < array.Length; i++)
        {
            action(ref array[i]);
        }
    }
}

...

new []
{
    InstanceOfProperty,
    InstanceOfProperty,
    InstanceOfProperty ...
}.Each((ref Property p) => p.Dimensions.Height = 100.0);

, Dimension , ( ). - :

new []
{
    InstanceOfProperty,
    InstanceOfProperty,
    InstanceOfProperty ...
}.Each((ref Property p) => p.Dimensions = new Dimension
                           {
                               Width = p.Dimensions.Width,
                               Height = 100.0
                           });

, , , ...

+1

Source: https://habr.com/ru/post/1762634/


All Articles