1

回答を追加できないため、質問を再度投稿しています。ここにコードがあります

static void Main(string[] args)
{
    string fileA= "B.txt";
    IList listA= new ArrayList();

    FileReader(fileA, ref listA);

    for (int i = 0; i < listA.Count; i++)
    {
        Console.WriteLine(listA[i].ToString());
    }

    Console.ReadKey();
}

public static void FileReader(string filename, ref IList result)
{
    using (StreamReader sr = new StreamReader(filename))
    {
        string firstName;
        string SecondName;

        while (!sr.EndOfStream)
        {
            firstName= sr.EndOfStream ? string.Empty : sr.ReadLine();
            SecondName= sr.EndOfStream ? string.Empty : sr.ReadLine();

            result.Add(new Person(firstName, SecondName));
        }
    }
}

そして、リストの値を [0] ={"firstname","lastname"} [1]={"firsname2","secondname2"} として取得しています

これらの値は Person クラスに関連付けられているため、インデックス [1] の姓の値を変更したい場合はどうすればよいですか? インデックス [1] の値を取得できますが、そのインデックスにリンクされている Person 変数にアクセスする方法

4

1 に答える 1

0

型情報を破棄するため、適切なデータ構造ではないを使用してArrayListいます (.NET 1.1 にこだわっていない限り)。

を使用してみてくださいList(T)

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

static void Main(string[] args)
{
    var file = "B.txt";
    var list = new List<Person>();

    ReadFile(file, list);

    list[1].LastName = "newValue";
}

private static void ReadFile(string file, List<Person> personList)
{
    var items = File.ReadLines(file)
                    // Take each value and tag it with its index
                    .Select((s, i) => new { Value = s, Index = i })
                    // Put the values into groups of 2
                    .GroupBy(item => item.Index / 2, item => item.Value)
                    // Take those groups and make a person
                    .Select(g => new Person { FirstName =  g.FirstOrDefault(), LastName = g.Skip(1).FirstOrDefault() });

    personList.AddRange(items);
}
于 2013-09-03T17:49:59.290 に答える