1

我有一组字符串需要存储在一组中,例如:

ID、名字、姓氏、城市、国家、语言

以上均适用于一个人(以身份证为代表)

现在我有 60 - 70 个(并且还在增长),我该如何组织它们?我查看了 NameValueCollection 类 - 它完全符合我的要求(如果我只有两个字段),但由于我有 6 个字段,所以我不能使用它。例如:

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

虽然这不起作用:(有人可以提出另一种实现这一目标的方法吗?

4

2 回答 2

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);
于 2012-06-16T12:50:54.403 回答
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"),
};
于 2012-06-16T12:55:30.310 回答