Reputation: 219
Is there a way in c# to have an array of multiple variables?
for instance, I have data for a stock:
10-01-2012| 10.00| 11.01| 9.56| 10.56
10-02-2012| 10.56| 10.99| 9.21| 9.99
10-03-2012| 9.99 | 10.12| 9.78| 10.11
What I would like to do, is create an array which takes a DateTime and a String variable, and outputs a double/string.
So, if I wanted to get the Open price of the stock on 10-01-2012, I could say
DateTime Day = Convert.ToDateTime("10-01-2012"); double openPrice = MyArray[Day,"Open"];
and it would return 10.00, as either a double or a string.
What is the best way to do this? Is this even possible with an array? If not, what other methods can I use? I have been thinking about this for a while, and I'm not sure the best way to structure this array/object
Thanks for any help!
Upvotes: 1
Views: 3022
Reputation: 334
You could use a dictionary within a dictionary, as follows:
var stocks = new Dictionary<DateTime, Dictionary<String, Double>>
Then, to access a price:
Double price = stocks[Day]["Open"]
Upvotes: 2
Reputation: 6527
Possibly better to make a single class to contain your data, and create an array or List of those;
class DailyPrice
{
DateTime Date { get; set; }
decimal Open { get; set; }
decimal Close { get; set; }
decimal High { get; set; }
decimal Low { get; set; }
}
static class Program
{
static void Main()
{
List<DailyPrice> prices = new List<DailyPrice>();
prices.Add(new DailyPrice() { Date = DateTime.Today, Open = 11.11M, Close=... });
prices.Add(new DailyPrice() { Date = DateTime.Today, Open = 12.14M, High=... });
...
}
}
Incidentally, due to precision problems when performing arithmetic with the double
type in C#, it's safer to user decimal
for monetary values (which I assume is what you have here).
Upvotes: 5
Reputation: 3105
as far as I know you can't do it with arrays, but you can achieve this with a Dictionnary<>:
Dictionnary<DateTime, double[]>
that way you will be able to have your values "indexed" by day, and then on position 0 of the double array you would have your "Open" value
to get the "10.00" value you need you would have to do this:
openvalue = mydic[Day][0];
Upvotes: 0