Dictionary <t,t> </t,t>的替代方案

时间:2012-06-30 12:39:40

标签: c# dictionary

我的申请要求我打印N次数值X.

所以,我可以这样做:

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

...以后我可以使用这些信息打印2页,两者都有文字值&#34; Hello World&#34;。

我遇到的问题是,词典真的希望第一个值是Key:

Dictionary<TKey, TValue>

因此,如果我想添加2页文本值&#34; Hello World&#34;然后是另外两个与#34; Goodbye World&#34;我有一个问题 - 它们都有一个TKey值为2,这会导致运行时错误(&#34;已经添加了具有相同键的项目&#34;)。

导致错误的逻辑:

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

我仍然需要使用这个概念/逻辑,但由于Key,我显然无法使用Dictionary类型。

有没有人有任何解决方法的想法?

4 个答案:

答案 0 :(得分:14)

我认为元组对于这项工作是完美的。

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"); 

而且......你可以很容易地将它包装成一个独立的类。

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
    }
  }
}

}

答案 1 :(得分:12)

使用列表&lt; T&gt;在这种情况下就足够了

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

答案 2 :(得分:1)

您可以使用词典,但键应该是字符串,而不是int;这毕竟是独一无二的!

那就是说,你不是在做查找,所以字典是不合适的。在这种情况下,史蒂夫的回答可能是最好的。

答案 3 :(得分:0)

嗯,我相信你有几个选择...

1。)在您的场景中,字符串本身似乎是关键,因此您可以反转参数的顺序

new Dictionary<string, int> ()

2。)如果在你的情况下有意义,可以使用Tuple甚至自定义类/结构。使用元组Chris已经向你展示了,所以我将向你展示我想到的“类解决方案”。

public class MyClass
{
    public string MyTextToPrint { get;set; }
    public string NumberOfPrints { get;set; }
    // any other variables you may need
}

然后只创建这些类的列表,与Tuple几乎相同,它只是一种更标准化的方式,因为也许你在其他地方也需要相同的功能,或者可能想要操纵它数据进一步。