Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace value in an array of struct c#

I have the following public struct in C#:

public struct Route
{
    public float Start; 
    public float End; 
    public float Range; 
    public bool InConstruction; 
};

I want to replace every property Range of Route used as an array of struct in an other class (Route[]). I did the following which works fine:

//dest.Route = new Route[]; 
for (var i = 0; i < dest.Route.Count; i++)
{
    dest.Route[i].Range = dest.Route[i].End - dest.Route[i].Start; 
}

Is there a way to optimize this loop or just other ways to implement this solution?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe with desc.Route.Select(i => i.Range = i.End – i.Start); ?

>Solution :

If you can’t change the struct, then no, you’ve done the most optimal thing. Even if you do find some solution with Linq, it’s eventually just going to boil down to a loop like you have.

If you’re dead set on using Linq, you’d need to do something like this:

desc.Route = desc.Route.Select(d => {
    d.Range = d.End - d.Start;
    return d;
})
.ToArray();

I’ll let you be the judge if that’s "better" for your project or not. This does go against some of the principles of Linq, mostly the "don’t cause side effects".

This:

.Select(i => i.Range = i.End - i.Start)

Doesn’t work (though it is legal syntax) because the assignment operator returns the value that was assigned, so you’d be selecting just the float assigned to the Range property, not the full Route object. https://dotnetfiddle.net/jSKZlj


If you can change the struct:

If Range is always the End field minus the Start field, then you could just compute it when you need to read the value, rather than preemptively. Shamelessly taking Etienne de Martel’s idea:

public struct Route
{
    public float Start; 
    public float End; 
    public float Range => End - Start;
    public bool InConstruction; 
};

Now there’s no need to do the loop calculation at all. The value for each object will be calculated as soon as you read the Range property.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading