There are two different variables here - the first is the Price
object(s), and the second is input.Prices
, which is a List of prices.
Your LINQ code takes the inputs.Prices
list, filters it and creates a new array from it, but all that does is create new collections. It doesn't change the actual objects that are in the collection. This is because classes, in C#, are all reference types, meaning that var price = input.Prices[0]
just copies the reference to a single, specific instance in memory. You can copy those references between a dozen lists and arrays, but the objects are the same.
It seems that what you want is to clone or copy by value your Price
objects. For that, you have two options:
- Make
Price
a struct.
Structs, unlike classes, are value types and are copied-by-value, meaning a new copy is made whenever you assign it to a new variable. This, however, has a performance penalty, since the whole struct is copied every time it's assigned. Your struct takes up 24-32 bytes (two 64bit double
s and two 32/64 bit references to string
s), which is more than the recommended rule of thumb of "no more than 16 bytes for structs", so it's probably a bad idea.
- Make a
Clone
method.
Have your Price
implement a Clone
method which returns a copy of the object - or alternately, create a copy-constructor that creates a new Price with the old values. Use that in your LINQ:
public class Price
{
// your fields
public Price Clone()
{
return new Price
{
Symbol = this.Symbol,
BidPrice = this.BidPrice,
//etc.
}
}
}
var p = input.Prices.Where(x => x.Exchange == exchange).Select(x => x.Clone()).ToArray();