2012-06-30 30 views
4

我的應用程序需要我打印N次量的值X的替代字典<T,T>

所以,我可以這樣做:

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

...後來我就可以使用此信息打印2個頁面,文本值爲「Hello World」。

我有問題,是字典真正想要的第一個值是關鍵:

Dictionary<TKey, TValue> 

因此,如果我想添加2頁與文本價值的「Hello World」,然後另外2與「再見世界」我有一個問題 - 他們都有一個TKey值爲2,這會導致運行時錯誤(「具有相同的密鑰項目已被添加」)。

這將導致一個錯誤的邏輯:

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

我還需要這個概念/邏輯的工作,但我顯然不能使用,由於關鍵的字典類型。

有沒有人有任何想法的工作?

回答

12

使用列表<牛逼>會在這種情況下

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 
+0

+1,因爲這正是我即將發佈的內容。 –

+1

這是我的第一個想法,但認爲有12人會毆打我,所以我提供了Tuple解決方案。 –

+0

嗯...它總是簡單的解決方案不是它..這裏我一直在尋找創建一個新的集合類型!謝謝。 – Dave

14

我認爲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 
    } 
    } 
} 

}

+2

+1用於Tuple – tehlexx

+0

謝謝 - 以前沒有聽說過Tuple。 更多信息:http://msdn.microsoft.com/en-us/library/system.tuple。aspx – Dave

+1

我認爲元組恰好在這裏,所以我們不必爲了容納一對元素而創建特定的類。 – MBen

0

好是不夠的,我相信你有幾個選擇...

1。 )在你的情況下,它似乎是字符串本身是關鍵,所以你可以扭轉你的參數的順序

new Dictionary<string, int>() 

2.)如果在您的情況下有意義,請使用Tuple或甚至自定義類/結構。 Chris已經向你展示了元組的用法,所以我會告訴你我想到的「class解決方案」。

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

,然後就創建這些類的列表,作品幾乎一樣的元組,它只是這樣做的更加規範的方式,因爲也許你會需要同其他地方的功能以及或許想要進一步操縱數據。

1

你可以使用字典,但鍵應該是字符串,而不是int;畢竟這是獨一無二的!

也就是說,你不查找字典是不合適的。儘管史蒂夫的回答可能是最好的。

相關問題