简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM