- Home /
c# - List with multiple types - Trading Engine - Stock Simulator
I'm trying to simulate a stock market (trading engine), where users can send "buy" or "sell" orders.
To achieve that, I think that I need a list with multiple types, something like:
List<string, string, float, float, int> myList = new List ........ ();
List<username, OrderType, Price, Amount, ID>
myList.Add("Robert", "buy", 15, 3, id); //So I could add new orders to the list like that
Is it possible to make a list like that? Or maybe is a better way to do it?
At this moment I have done it with
Dictionary<string, Dictionary<string, float>>
Dictionary<username, Dictionary<valueType, Value>> //valueType can be used for "amount", "price" and "ID"
and I've successfully created what you can see in the image. But I want to add more functions to my market and it seems very difficult to do it this way, so if you know a better way, I would really apprecciate your help :)
Thank you in advance for your time :)
Answer by dillonburton85 · Jul 31, 2018 at 12:23 AM
You need Objects. Create a class called 'Order' with the following:
public class Order {
public int ID { get; set; }
public string Username { get; set; }
public int Amount { get; set; }
public float Price { get; set; }
public Order(int ID, string Username, int Amount, float Price) {
this.ID = ID;
this.Username = Username;
this.Amount = Amount;
this.Price = Price;
}
}
Then add the objets to a list elsewhere, like this:
List<Order> orders = new List<Order>();
var order1 = new Order(0, "Joe", 5, 2.5f);
var order2 = new Order(1, "Smith", 3, 3.7f);
orders.Add(order1);
orders.Add(order2);
If you wanted to access the Username of the first order you added, you can do so like this:
orders[0].Username
For printing purposes (like you are doing in this example) you will want to create a loop to display the values of the array:
foreach (var order in orders) {
Debug.Log(order.Username);
Debug.Log(order.Amount);
// ...
}
Of course you won't be using Debug.Log, you will be putting the values into your UI.
Thank you very much! That is exactly what I was looking for!
Answer by Ziplock9000 · Oct 30, 2020 at 02:04 AM
Use Tuples:
Similar to what @dillonbro said except in recent years you don't need to create your own class, you can use Tuples:
https://stackoverflow.com/questions/8002455/how-to-easily-initialize-a-list-of-tuples
Your answer
Follow this Question
Related Questions
How can I call the Load method and/or the ShootingSettings method also only once in the Update ? 1 Answer
How can I add a speed factor to the script ? 0 Answers
How can i check and fire an event when the user look at specific object ? 0 Answers
Sorting a list based of a variable 1 Answer
How can i List objects by name but also in small text or big text or any kind ? 1 Answer