4

我的应用程序要求我打印 N 次值 X。

所以,我可以这样做:

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

...稍后我可以使用此信息打印 2 页,均带有文本值“Hello World”。

我遇到的问题是 Dictionary 真的希望第一个值是键:

Dictionary<TKey, TValue>

因此,如果我想添加 2 个带有文本值“Hello World”的页面,然后再添加 2 个带有“Goodbye World”的页面,我有一个问题 - 它们的 TKey 值都是 2,这会导致运行时错误(“一个项目已经添加了相同的密钥”)。

会导致错误的逻辑:

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

我仍然需要这个概念/逻辑来工作,但由于 Key 的原因,我显然不能使用 Dictionary 类型。

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

4

4 回答 4

15

我认为 Tuple 非常适合这项工作。

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

}

于 2012-06-30T12:42:55.250 回答
13

在这种情况下使用 List<T> 就足够了

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
于 2012-06-30T12:43:50.173 回答
1

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

也就是说,您没有进行查找,因此字典是不合适的。不过,在这种情况下,史蒂夫的回答可能是最好的。

于 2012-06-30T12:52:06.150 回答
0

好吧,我相信你在这里有几个选择......

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

new Dictionary<string, int> ()

2.) 如果对您的情况有意义,请使用元组甚至自定义类/结构。元组 Chris 的用法已经向您展示过,所以我将向您展示我想到的“类解决方案”。

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

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

于 2012-06-30T12:51:16.840 回答