2012-11-19 24 views
0

我使用以下代码将数据存储在数组中,然后将其打印出来。如何从txtfile读取,然后将信息传递给另一个类c#

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

@MicahArmantrout只有2个问题,他并没有接受一个答案,这是其中之一... ...可能要检查多少问题80%的解决方案从中计算。 – Jelly

+0

@jelly好电话 –

+0

这与wpf有什么关系? –

回答

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++ 

     } 

} 
+0

谢谢你!正是我需要的! –

+0

你可能想要检查'words.Length> = 4'来确保一个简短的行不会导致一个'IndexOutOfRangeException'如果这对你的任务有帮助的话不会有任何线索。 – Thymine

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(); 

你应该注意的是,这里没有提供解决方案具有良好的异常处理。

+0

谢谢奥斯汀!由于分配,我不喜欢使用LINQ。 –