2011-12-11 25 views
5

例如,我在我的應用程序類型是什麼有一個人的名字,因爲它的名字,並擁有兩個值的列表。該類型的名稱是人的名稱和類型只包含自己的年齡和性傳播疾病的人數。什麼是用於保持兩個值了良好的數據結構?

我的第一個想法是使的一類人與在年齡和NumStds在構造函數是必需的,創建一個列表,我可以添加到年齡和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)); 
} 

我只是想知道如果有一個數據結構,在那裏我可以僅僅將元素的列表<>由他們的名字和重視他們的屬性來湊湊熱鬧。就像我可以說

people.Remove(Julie) 
+2

如果有兩個同名的人呢? – TrueWill

回答

1

看看KeyedCollection<TKey, TValue> Class

KeyedCollection < TKEY的,TValue >類

提供抽象基類的集合,其中的鍵被嵌入的值。

你需要從這個抽象類,例如派生自己的集合類

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

例子:

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

請注意,您的Person類的名稱屬性應該是不變的(只讀)。

+0

嗚呼!謝謝:D –

5

這聽起來像你正在尋找一個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。這需要更多的工作來實施,但可能有用。

爲了使這項工作,創造人的集合類並重寫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"); 
1

我不知道你的要求,只是看你刪除你的帖子的末尾()語句,你可以得到一個LINQ表達同樣的效果。

people.Remove(p => string.Compare(p.Name, "Julia", true) == 0); 
+2

使用string.Equals()而不是string.Compare() – slugster

0

使用此一Dictionary<string, Person>的問題是,你可以有不匹配的人的名字的關鍵。這是可以避免的,但我寧願使用HashSet<Person>作業。性能是一樣的。

您只需要通過覆蓋GetHashCode來準備您的班級以返回Name的哈希碼。

public override int GetHashCode() 
{ 
    return Name.GetHashCode(); 
} 
相關問題