Adding an item to a Tuple in C#
35,065
Solution 1
use List
var games = new List<Tuple<string, Nullable<double>>>()
{
new Tuple<string, Nullable<double>>("Fallout 3: $", 13.95),
new Tuple<string, Nullable<double>>("GTA V: $", 45.95),
new Tuple<string, Nullable<double>>("Rocket League: $", 19.95)
};
games.Add(new Tuple<string, double?>( "Skyrim", 15.10 ));
Solution 2
Although the other answers already cover what you should be doing i.e. using a List
(code taken from this answer):
var games = new List<Tuple<string, Nullable<double>>>()
{
new Tuple<string, Nullable<double>>("Fallout 3: $", 13.95),
new Tuple<string, Nullable<double>>("GTA V: $", 45.95),
new Tuple<string, Nullable<double>>("Rocket League: $", 19.95)
};
And then you can call the Add
method:
games.Add(new Tuple<string, double?>("Skyrim: $", 15.10));
I'd like to point out a few things you can do to improve your code.
-
The
string
in theTuple
should just be the game name, you can always format it later:string formattedGame = $"{game.Item1}: ${game.Item2}";
There doesn't seem to be much need for using
Nullable<double>
(can also be written asdouble?
BTW), consider just using adouble
.- When dealing with monetary values it is advisable to use
decimal
, so consider switching to that. - Consider using a custom class i.e.
Game
. This will simplify the code and help later on when you want to add more details i.e.Description
,Genre
,AgeRating
etc.
For more detail on when to use an array or a list see this question, however, the short version is you should probably be using a list.
Solution 3
Use Resize
method:
Array.Resize(ref games, games.Length + 1);
games[games.Length - 1] = new Tuple<string, Nullable<double>>("Star Flare: $", 5.00),;
Author by
Tech Dynasty
Updated on July 05, 2022Comments
-
Tech Dynasty over 1 year
I have a tuple array as shown below;
var games = new Tuple <string, Nullable<double>>[] { new Tuple<string, Nullable<double>>("Fallout 3: $", 13.95), new Tuple<string, Nullable<double>>("GTA V: $", 45.95), new Tuple<string, Nullable<double>>("Rocket League: $", 19.95) };
I am wondering if there is a function would let me add another item to this list.
Please help!
Thanks, Sean