c# - 什么是用于保存两个值的良好数据结构?

标签 c# data-structures

例如,我的应用程序中有一个类型列表,其中包含一个人的名字并包含两个值。类型的名称是人名,类型仅包含他们的年龄和性病数量。

我的第一个想法是创建一个具有 Age 和 NumStds 属性的 Persons 类,其中 Age 和 NumStds 在构造函数中是必需的,并创建一个我可以添加到其中的列表。

class Person
{
    public string Name { get; set; }
    public int NumSTDs { get; set; }
    public int Age { get; set; }

    public Person(string name, int age, int stds)
    {
        Name = name;
        Age = age; 
        NumSTDs = stds; 
    }
}

static void Main(string[] args)
{
    List<Person> peoples = new List<Person>();
    peoples.Add(new Person("Julie", 23, 45)); 
}

我只是想知道是否有一种数据结构,我可以通过它们的名称引用 List<> 中的元素,并让附加到它们的属性随行。就像我可以说的那样

people.Remove(Julie) 

最佳答案

听起来您正在寻找 Dictionary .

Dictionary<string, Person> peoples = new Dictionary<string, Person>();
Person oPerson = new Person("Julie", 23, 45); 
peoples.Add(oPerson.Name, oPerson); 

另一个选项是 System.Collections.ObjectModel.KeyedCollection .这需要做更多的工作才能实现,但很有用。

要完成这项工作,请为 person 创建一个集合类并覆盖 GetKeyForItem 方法:

public class PersonCollection : System.Collections.ObjectModel.KeyedCollection<string, Person>
{
    protected override string GetKeyForItem(Person item)
    {
        return item.Name;
    }
}

然后您可以像您的示例一样将项目添加到集合中:

PersonCollection peoples = new PersonCollection();
peoples.Add(new Person("Julie", 23, 45));

然后删除项目:

peoples.Remove("Julie");

关于c# - 什么是用于保存两个值的良好数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8461805/

相关文章:

c# - Unity 中使用 Instantiate(Resources.load) 方法缺少纹理的问题

c - 链表 : How to Sort Doubly Linked List?

c - 实现二叉搜索树 - "incompatible types when returning type ' struct item_t *'..."

c# - “System.Web.WebPages.Html.HtmlHelper”不包含“ActionLink”的定义

c# - 模型中的razor foreach无法使用

algorithm - 使用最大堆与平衡 BST 实现优先级队列

c++ - c++ 中是否有任何众所周知的基于文件的键-> 值数据结构可用?

python - Python(或 C)中的内存高效字符串到字符串映射

c# - Protobuf-net 和泛型

c# - 如何将二维字符串数组转换为二维 [int, double, bool, ..] 数组?