Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An alternative to Dictionary<T,T>

Tags:

c#

dictionary

My application requires I print N amount of times the Value X.

So, I can do this:

Dictionary<int, string> toPrint = new Dictionary<int, string>();
toPrint.Add(2, "Hello World");

...and later on I can use this information to print 2 pages, both with the text value "Hello World".

The issue I have, is the Dictionary really wants the first value to be the Key:

Dictionary<TKey, TValue>

Therefore, if I want to add 2 pages with the text value "Hello World" and then another 2 with "Goodbye World" I have an issue - both of them have a TKey value of 2 and this causes a runtime error ("An item with the same key has already been added").

The logic which will causes an 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 to work, but I obviously can't use the Dictionary type due to the Key.

Does any one have any ideas of a work around?

like image 350
Dave Avatar asked Nov 27 '22 11:11

Dave


2 Answers

I think a Tuple would 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 could easily wrap this into a self contained 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
    }
  }
}

}

like image 142
Chris Gessler Avatar answered Dec 23 '22 05:12

Chris Gessler


Using a List<T> will be enough 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
like image 32
Steve Avatar answered Dec 23 '22 05:12

Steve