0

次のコードを使用してデータを配列に保存し、それを出力します。

Person[] people = {new Person( "Loki", "Lo", "Asgard", 2050),
                              new Person( "Thor", "Th", "Asgard", 2050),
                              new Person( "Iron", "Man", "Il", 4050),
                              new Person( "The", "Hulk", "Green", 1970)};

今、これらの情報を含むテキスト行から読み取り、同じ配列を使用したいと考えています。方法?

txtファイルは次のようになります

The Hulk Green 1970
Iron Man Il 4050
Thor Th Asgard 2050
Loki Lo Asgard 2050

単語を文字列配列に格納し、各単語に [0]、[1] などを使用することを考えています。しかし、1人の「人」だけを使いたいので、ループは問題を引き起こします。助言がありますか?

4

2 に答える 2

2

Personデータの「行」を取得し、それに応じて解析するコンストラクターを追加します。

次に、これを行うことができます:

var people = File.ReadLines("yourFile.txt")
                 .Select(line => new Person(line))
                 .ToArray();

追加のコンストラクターが必要ない場合:

var people = File.ReadLines("yourFile.txt")
                 .Select(line => line.Split())
                 .Select(items => new Person(item[0], item[1], item[2], Convert.ToInt32(item[3]))
                 .ToArray();

ここで提供されているどちらのソリューションにも、優れた例外処理がないことに注意してください。

于 2012-11-19T21:07:15.707 に答える
1

ここにLinqを使用しないソリューションがあります

Person[] people= new Person[4];
using(var file = System.IO.File.OpenText(_LstFilename))
{
   int j=0;
 while (!file.EndOfStream)
    {
        String line = file.ReadLine();

        // ignore empty lines
        if (line.Length > 0)
        {    

            string[] words = line.Split(' ');
             Person per= new Person(words[0], words[1], words[2], Convert.ToInt32(words[3]));

             people[j]=per;
             j++

        }

}
于 2012-11-19T21:15:29.580 に答える