1

次のような文字列のセットをセットに格納する必要があります。

id、名、姓、都市、国、言語

上記のすべてが1人の人に適用されます(IDで表されます)

今、私はこれらの60〜70を持っています(そして成長しています)、どうすればそれらを整理できますか?私はNameValueCollectionクラスを見てきました-そしてそれは私が望むことを正確に行います(私が2つのフィールドしかない場合)、しかし私は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 に答える