2016-11-26 110 views
0

我在阅读文件时遇到问题。保存仅结束行

我必须编写程序,从波兰彩票的数字(保存在.txt),并将其添加到列表并回答问题。

反正..我的算法仅保存端线。我要保存所有的行列表.. :)

 string line; 
     List<Losuj> losowanko = new List<Losuj>(); 

     Losuj pomocnik = new Losuj(); 


     StreamReader file = 
       new StreamReader(@"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt"); 
      while ((line = file.ReadLine()) != null) 
      { 
      // Console.WriteLine(line); 
      string[] podzialka = line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None); 



      pomocnik.NumerLosowania = Int32.Parse(podzialka[0]); 
      pomocnik.JakiDzien = Int32.Parse(podzialka[2]); 
      pomocnik.JakiMiesiac =Int32.Parse(podzialka[3]); 
      pomocnik.JakiRok=Int32.Parse(podzialka[4]); 
       for (int i = 5, lo=0; i < 11; i++,lo++) 
      { 
       pomocnik.Los[lo] =Int32.Parse(podzialka[i]); 
      } 
      losowanko.Add(pomocnik); 

     } 


     file.Close(); 

回答

6

移动Losuj对象创建行while循环里面,否则你正在改变和增加同一个对象连连

using(StreamReader file = 
      new StreamReader(@"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt")) 
    { 
     while ((line = file.ReadLine()) != null) 
     { 
     Losuj pomocnik = new Losuj(); 
     // Console.WriteLine(line); 
     string[] podzialka = line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None); 

     pomocnik.NumerLosowania = Int32.Parse(podzialka[0]); 
     pomocnik.JakiDzien = Int32.Parse(podzialka[2]); 
     pomocnik.JakiMiesiac =Int32.Parse(podzialka[3]); 
     pomocnik.JakiRok=Int32.Parse(podzialka[4]); 
      for (int i = 5, lo=0; i < 11; i++,lo++) 
     { 
      pomocnik.Los[lo] =Int32.Parse(podzialka[i]); 
     } 
     losowanko.Add(pomocnik); 
     } 
    } 
0

为了避免这样的错误(错误列表项创建),我建议通过产生losowanko的LINQ。你应该

  • 由线读取文件
  • 分割每行
  • 创建Losuj例如
  • 兑现的IEnumerable<Losuj>List<Losuj>

实现:

List<Losuj> losowanko = File 
    .ReadLines(@"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt") 
    .Select(line => line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None)) 
    .Select(items => { 
     Losuj item = new Losuj() { 
      NumerLosowania = Int32.Parse(items[0]), 
      JakiDzien  = Int32.Parse(items[2]), 
      JakiMiesiac = Int32.Parse(items[3]), 
      JakiRok  = Int32.Parse(items[4])}; 

     for (int i = 5, lo = 0; i < 11; i++, lo++) 
      item[lo] = Int32.Parse(items[i]); 

     return item;}) 
    .ToList();