Alternative to dictionary <T, T>
My application requires me to print N number of times the value of X.
So, I can do this:
Dictionary<int, string> toPrint = new Dictionary<int, string>(); toPrint.Add(2, "Hello World"); ... and later I can use this information to print 2 pages, as with the text value "Hello World".
The problem I have is that the dictionary really wants the key to be the first value:
Dictionary<TKey, TValue> Therefore, if I want to add 2 pages with the text value "Hello World", and then 2 more with "Goodbye World", I have a problem - both of them have a value of TKey 2, and this causes a runtime error ("Element with the same key has already been added ").
The logic that will lead to the error:
Dictionary<int, string> toPrint = new Dictionary<int, string>(); toPrint.Add(2, "Hello World"); toPrint.Add(2, "Goodbye World"); I still need this concept / logic, but I obviously cannot use the dictionary type because of the key.
Does anyone have any ideas about work?
Using the <T> list will be sufficient in this case.
class PrintJob { public int printRepeat {get; set;} public string printText {get; set;} // If required, you could add more fields } List<PrintJob> printJobs = new List<PrintJob>() { new PrintJob{printRepeat = 2, printText = "Hello World"}, new PrintJob{printRepeat = 2, printText = "Goodbye World"} } foreach(PrintJob p in printJobs) // do the work I think Tuple will be perfect for this job.
List<Tuple<int, string>> toPrint = new List<Tuple<int, string>>(); toPrint.Add(new Tuple<int, string>(2, "Hello World"); toPrint.Add(new Tuple<int, string>(2, "Goodbye World"); And ... you can easily turn this into a standalone class.
public class PrintJobs { // ctor logic here private readonly List<Tuple<int, string>> _printJobs = new List<Tuple<int, string>>(); public void AddJob(string value, int count = 1) // default to 1 copy { this._printJobs.Add(new Tuple<int, string>(count, value)); } public void PrintAllJobs() { foreach(var j in this._printJobs) { // print job } } } }
Well, I think you have a couple of options ...
1.) in your script, it seems that the string itself is the key, so you can just change the order of your parameters
new Dictionary<string, int> () 2.) Use a Tuple or even a custom class / structure if that makes sense in your situation. Chris has already shown you the use of the tuple, so I will show you the βcool solutionβ that I have in mind.
public class MyClass { public string MyTextToPrint { get;set; } public string NumberOfPrints { get;set; } // any other variables you may need } and then just creating a list of these classes works almost the same as Tuple, it's just a more standardized way to do this, because you might need the same functions in other places, or maybe you want to manipulate the data further.