例如,我的应用程序中有一个类型列表,其中包含一个人的名字并包含两个值。类型的名称是人名,类型仅包含他们的年龄和性病数量。
我的第一个想法是创建一个具有 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/