简体   繁体   English

替换struct c#数组中的值

[英]Replace value in an array of struct c#

I have the following public struct in C#:我在 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[]).我想替换在另一个类 (Route[]) 中用作结构数组的每个属性 Range of 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);也许使用 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.即使您确实使用 Linq 找到了一些解决方案,它最终也会像您一样归结为一个循环。

If you're dead set on using Linq, you'd need to do something like this:如果你死心塌地使用 Linq,你需要做这样的事情:

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".这确实违反了 Linq 的一些原则,主要是“不引起副作用”。

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.不起作用(尽管它是合法的语法),因为赋值运算符返回已分配的值,因此您将仅选择分配给 Range 属性的浮点数,而不是完整的 Route 对象。 https://dotnetfiddle.net/jSKZlj 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.如果Range始终End字段减去Start字段,那么您可以在需要读取 value 时计算它,而不是先发制人。 Shamelessly taking Etienne de Martel's idea :无耻地接受Etienne de Martel 的想法

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.读取Range属性后,将立即计算每个对象的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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