2012-06-16 22 views
0

我有一組串的,我需要在一組存儲,如:用的NameValueCollection類存儲多於兩個值

ID,名字,姓氏,城市,國家,語言

所有以上適用於一個人(以身份證爲代表)

現在我有60-70個這樣的(並且在增長),我怎麼能組織他們?我查看了NameValueCollection類 - 它完全符合我的要求(如果我只有兩個字段),但由於我有6個字段,因此我無法使用它。例如:

public NameValueCollection personCollection = new NameValueCollection 
    { 
     { "harry", "townsend", "london", "UK", "english" }, 
     { "john", "cowen", "liverpool", "UK", "english" }, 
     // and so on... 
    }; 

雖然這並不工作:(可能有人認爲實現這一目標的另一種方式

回答

1

如果你絕對不希望創建任何新的類,你可以用列表的字典,通過您的ID鍵:

IDictionary<string, IList<string>> personCollection = 
    new Dictionary<string, IList<string>> 
{ 
    { "1", new [] { "harry", "townsend", "london", "UK", "english" }}, 
    { "2", new [] { "john", "cowen", "liverpool", "UK", "english" }}, 
}; 

...然後你可以訪問使用字典和列表索引:

Console.WriteLine(personCollection["1"][0]); // Output: "harry" 
Console.WriteLine(personCollection["2"][2]); // Output: "liverpool" 

但是,正確的OOP方法是定義與性質一類爲您的每串:

public class Person 
{ 
    public string Id { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string City { get; set; } 
    public string Country { get; set; } 
    public string Language { get; set; } 

    public Person() { } 

    public Person(string id, string firstName, string lastName, 
        string city, string country, string language) 
    { 
     this.Id = id; 
     this.FirstName = firstName; 
     this.LastName = lastName; 
     this.City = city; 
     this.Country = country; 
     this.Language = language; 
    } 
} 

你可以然後創建人的名單:

IList<Person> persons = new List<Person>() 
{ 
    new Person("1", "harry", "townsend", "london", "UK", "english"), 
    new Person("2", "john", "cowen", "liverpool", "UK", "english"), 
}; 
+0

Downvoter謹慎解釋? – Douglas

2

你怎麼樣讓與屬性的Person類需要

public class Person 
{ 
    public int id { get; set; } 
    public string firstname { get; set; } 
    public string lastname { get; set; } 
    // more attributes here 
} 

然後? ,只是實例化Person類並創建新的Person對象。 然後,您可以將這些人添加到列表中。

 Person somePerson = new Person(); 
     somePerson.firstname = "John"; 
     somePerson.lastname = "Doe"; 
     somePerson.id = 1; 

     List<Person> listOfPersons = new List<Person>(); 
     listOfPersons.Add(somePerson); 
+0

嗨,我真的不希望有創建的每個人一個新的對象,我寧願希望能夠引用它像一個多維數組 – user1460619

+0

好你不必須爲每個人創建一個新對象,就像@Steve發佈的那樣,您可以直接將它們添加到列表中: persons.Add(新PersonData {id = 1,firstname =「John」,lastname =「Reed」} – Thousand

+0

@ user1460619爲什麼?這是一個非常優雅的方式。 –