2016-11-07 6 views
0

ファイルをリストに読み込んでいて、ボタンを押してリストからランダムなエントリを取得したい。私はVBでこれを行うことができますが、かなり新しいC#です。私はリストを公開させなければならないことを知っているが、ますます不満を感じている。 以下のコードは、ファイルをリストに、その後リストボックスを読み込みます。あなたは1つのメソッド内のいくつかの情報を処理し、別のメソッド内でこの処理された情報を使用したい場合はCで異なるメソッド間のリストを使用する#

namespace texttoarray 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      int counter = 0; 
      string line; 
      var list = new List<string>(); 
      var file = new StreamReader(@"list.txt"); 
      while ((line = file.ReadLine()) != null) 
      { 
       list.Add(line); 
       counter++; 
      } 

      listBox2.DataSource = list; 

      var rnd = new Random(); 
     } 
    } 
} 
+2

正確にはどのような問題がありますか?すべての例外メッセージ? – Udontknow

+0

あなたは何をしたいの詳細を教えていただけますか? – staticvoidmain

+1

[code] list [index]; [code]でリストから項目を取得するには、[code] int index = rnd.NextInt(0、list.count-1); [code] 。 –

答えて

0

は、次のことができます。

  • 保つ

    • は、第二のメソッドに引数として情報を渡しますあなたのクラスの中の情報をどんなメソッドの中でも使うことができます。

    私はあなたのために2番目のアプローチをとるでしょうから、

    static class Program 
    { 
        // list inside your class with the information you need 
        private static List<string> fileLines; 
    
        private static void Main(string[] args) 
        { 
         // call the method to read your file and create the list 
         FirstMethod(); 
    
         // second method to get a random line, in this case, will return the string 
         var result = SecondMethod(); 
    
         Console.WriteLine(result); 
         Console.ReadLine(); 
        } 
    
        private static void FirstMethod() 
        { 
         // with this approach you can load one line per string inside your List<> 
         var yourFile = File.ReadAllLines("C:\\test.txt"); 
         fileLines = new List<string>(yourFile); 
        } 
    
        private static string SecondMethod() 
        { 
         // random number starting with 0 and maximum to your list size 
         var rnd = new Random(); 
         return fileLines[rnd.Next(0, fileLines.Count)]; 
        } 
    } 
    
  • 関連する問題