2016-11-26 9 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

(間違ったリスト項目の作成を)このようなエラーを避けるために、私は経由でのLINQlosowankoを生成示唆しています。

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(); 
:あなたは

  • がマテリアライズ作成線でIEnumerable<Losuj>

List<Losuj>への実装をLosujインスタンスを

  • スプリット各行
  • をファイルをお読みください
  • 関連する問題