Cra*_*len 5 c# data-structures
例如,我在我的应用程序中有一个类型的列表,其中有一个人名作为其名称并保存两个值.类型的名称是人员姓名,类型仅包含他们的年龄和std的数量.
我的第一个想法是创建一个具有Age和NumStds属性的Person类,其中在构造函数中需要Age和NumStds,并创建一个我可以添加的List.
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));
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道是否有一个数据结构,我可以通过它们的名称来引用List <>中的元素,并且附加了它们的属性.就像我说的那样
people.Remove(Julie)
Run Code Online (Sandbox Code Playgroud)
听起来你正在寻找一本词典.
Dictionary<string, Person> peoples = new Dictionary<string, Person>();
Person oPerson = new Person("Julie", 23, 45);
peoples.Add(oPerson.Name, oPerson);
Run Code Online (Sandbox Code Playgroud)
另一个选项是System.Collections.ObjectModel.KeyedCollection.这需要更多的工作来实现,但可能很有用.
要使其工作,请为person创建一个集合类并重写GetKeyForItem方法:
public class PersonCollection : System.Collections.ObjectModel.KeyedCollection<string, Person>
{
protected override string GetKeyForItem(Person item)
{
return item.Name;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像在示例中一样将项添加到集合中:
PersonCollection peoples = new PersonCollection();
peoples.Add(new Person("Julie", 23, 45));
Run Code Online (Sandbox Code Playgroud)
然后删除该项目:
peoples.Remove("Julie");
Run Code Online (Sandbox Code Playgroud)
看一下KeyedCollection<TKey, TValue> Class。
KeyedCollection<TKey, TValue> 类
提供其键嵌入值中的集合的抽象基类。
您需要从这个抽象类派生您自己的集合类,例如
class PersonCollection : KeyedCollection<string, Person>
{
protected override string GetKeyForItem(Person item)
{
return item.Name;
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
static void Main(string[] args)
{
var peoples = new PersonCollection();
var julie = new Person("Julie", 23, 45)
peoples.Add(julie);
people.Remove(julie);
// - or -
people.Remove("Julie");
}
Run Code Online (Sandbox Code Playgroud)
请注意,Person 类的 Name 属性应该是不可变的(只读)。