2013-05-01 20 views
2

我想在C#某種方式進行硬編碼信息如下:如何在C#中存儲數據元組?

1423, General 
5298, Chiro 
2093, Physio 
9685, Dental 
3029, Optics 

我想然後參考該數據如下:

"The description for category 1423 is " & MyData.GetDescription[1423] 
"The id number for General is " & MyData.GetIdNumber("General") 

什麼是做的最好辦法這在C#中?

+6

什麼用字典的錯誤? – DGibbs 2013-05-01 07:49:00

+0

@DGibbs在C#中可用嗎? – CJ7 2013-05-01 07:49:53

+0

[絕對](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx) – DGibbs 2013-05-01 07:52:42

回答

6

那麼你可以使用Tuple<int, string> - 但我建議創建一個類來存儲兩個值:

public sealed class Category 
{ 
    private readonly int id; 
    public int Id { get { return id; } } 

    private readonly string description; 
    public string Description { get { return description; } } 

    public Category(int id, string description) 
    { 
     this.id = id; 
     this.description = description; 
    } 

    // Possibly override Equals etc 
} 

然後進行查找的目的,你既可以有描述查找一個Dictionary<string, Category>Dictionary<int, Category>對於ID查找 - 或者如果您確信類別數量保持不變,則可以使用List<Category>

有過使用這種命名類型的好處只是一個Tuple或簡單Dictionary<string, int>Dictionary<int, string>是:

  • 你有,你可以繞過一個具體類型,在你的數據模型等
  • 使用你會不會落得這是邏輯上的任何其他數據混淆類型一Category只是一個intstring
  • 您的代碼會更清楚,當它使用01閱讀和Description特性比Item1Item2Tuple<,>
  • 如果您需要稍後添加其他屬性,則更改量很小。
+0

大多數時候,我發現自己比字典更喜歡自定義類。這很容易擴展,並且Dictionary通常不能滿足我的要求(即使對於組合框文本 - >值)。在哪種情況下Dictionary最好? – Fendy 2013-05-01 08:00:27

+0

@Fendy:我通常在使用字典的時候,只需*希望通過基於散列的查找獲得一個集合。目前還不清楚你在考慮什麼樣的情況。 – 2013-05-01 08:11:58

3

你可以使用一個Dictionary<TKey, TValue>

var items = new Dictionary<int, string>(); 
items.Add(1423, "General"); 
... 

var valueOf1423 = items[1423]; 
var keyOfGeneral = items.FirstOrDefault(x => x.Value == "General").Key; 

上面的例子會拋出一個異常,如果有一個與價值「常規」沒有項目。爲了防止出現這種情況,您可以將Dictionary包裝在自定義類中,並檢查條目是否存在並返回所需的任何內容。

請注意,該值不是唯一的,Dictonary允許您使用不同的鍵存儲相同的值。

包裝類可能是這個樣子:

public class Category { 
    private Dictionary<int, string> items = new Dictionary<int,, string>(); 

    public void Add(int id, string description) { 
     if (GetId(description <> -1)) { 
      // Entry with description already exists. 
      // Handle accordingly to enforce uniqueness if required. 
     } else { 
      items.Add(id, description); 
     } 
    } 

    public string GetDescription(int id) { 
     return items[id]; 
    } 

    public int GetId(string description) { 
     var entry = items.FirstOrDefault(x => x.Value == description); 
     if (entry == null) 
      return -1; 
     else 
      return entry.Key; 
    } 
}