如何在c#中存储数据元组

本文关键字:存储 数据 元组 | 更新日期: 2023-09-27 18:11:32

我想在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#中做这件事的最好方法是什么?

如何在c#中存储数据元组

可以使用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
  • 当你使用IdDescription属性时,你的代码将比Tuple<,>中的Item1Item2更清晰。
  • 如果你需要添加另一个属性,更改是最小的

您可以使用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;

上面的例子将抛出一个异常,如果没有值为"General"的项。为了防止这种情况,你可以将Dictionary包装在一个自定义类中,检查条目是否存在,并返回你需要的任何内容。

注意值不是唯一的,字典允许您用不同的键存储相同的值。

包装器类可以像这样:

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