I am really new in c# programming. I searched several hours, but can't find a solution or I don't understand how can I solve this problem. I deserialized objects from a dataset. my objects have trading specific values for example open high low close. I want to iterate through my objects and get some values in a float array. the array should look like this float[] rsi14 ={ 7520.5, 7535.0, 7530.5, ...}
Like this:
deserialziedObjectRsi[0].open + desirializedObjectRsi[1].open + ... to array.
These values are already from type float.
I want this in a loop, so I don't have to write this 50 times or more.
Here is some code that I have tried:
var deserializedObjectRsi =
JsonConvert.DeserializeObject<List<HistoricPricesRsi>>(stochDataRSI);
List<float> RsiClose = new List<float>();
RsiClose.Add(deserializedObjectRsi[0].close);
RsiClose.Add(deserializedObjectRsi[1].close);
RsiClose.Add(deserializedObjectRsi[2].close);
RsiClose.Add(deserializedObjectRsi[3].close);
RsiClose.Add(deserializedObjectRsi[4].close);
RsiClose.Add(deserializedObjectRsi[5].close);
RsiClose.Add(deserializedObjectRsi[6].close);
RsiClose.Add(deserializedObjectRsi[7].close);
RsiClose.Add(deserializedObjectRsi[8].close);
RsiClose.Add(deserializedObjectRsi[9].close);
RsiClose.Add(deserializedObjectRsi[10].close);
RsiClose.Add(deserializedObjectRsi[11].close);
RsiClose.Add(deserializedObjectRsi[12].close);
RsiClose.Add(deserializedObjectRsi[13].close);
float[] arrRSI14 = RsiClose.ToArray();
You can use LINQ to process the data for you in a declarative way. There will be an implied loop in it.
var arrRSI14 = deserializedObjectRsi.Select(x => Convert.ToSingle(x.Close)).ToArray();
What that does is, for each value (represented as x
, but you can use any name which makes sense) in deserializedObjectRsi
, convert it to a single, and put the results into an array. The var
keyword makes the compiler figure out what the type is; you could write float[]
if you really wanted to.
In C#, the float
keyword is an alias of the .NET Framework Single
type (please see C# Float vs. VB.net Single - Namin' complainin' for more information), which is why the .NET Convert method shown uses ToSingle instead of ToFloat.
I wish to add a note on the data type used: a Single, or float, is often a poor choice for monetary data as its precision is small enough that noticeable errors accumulate quickly if they are used in calculations. I recommend using the Decimal type when it is important that numbers are not approximated to binary fractions behind the scenes, for example 0.1 in decimal is a recurring binary fraction and cannot be represented exactly in a Single or Double.
For an informative read:What Every Computer Scientist Should Know About Floating-Point Arithmetic .
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.