2013-03-01 53 views
0

我想爲c#窗體表單應用程序的一些指導,以便能夠將一整列數字放入一個列表中,數據將成爲文本庫,例如它會包含4列是這樣的:如何將一列數據放入列表中的c#

100 200 300 400 
100 200 300 400 
101 292 83 7312 

我可以把整個文本列表,但我希望能有4個不同的列表,並把每個列到自己的名單如果讓SENCE。

我需要閱讀每一行和一些如何把一個拆分然後添加到列表?

Ps。我不希望代碼只是能夠做到這一點的最好方法,如果我在正確的軌道上?

+0

如果這些列是相關的,爲什麼不將它們存儲在數據表中? – AbZy 2013-03-01 21:12:03

+0

你有什麼嘗試?你是從一個文件,一個UI控件中讀取文本嗎? – 2013-03-01 21:13:21

+0

我想使用一個列表,所以我可以使用它們來進一步的功能,如總列ect和它來自一個文件,所以我正在使用流讀取器。謝謝 – user2125084 2013-03-01 21:23:54

回答

0

我不會將值讀入單獨的列表。如果你維護單獨的列表,你需要擔心保持所有的列表同步。我會創建一個對象,您可以使用它來保存一行中的所有信息。

public class Entry 
{ 
    // give meaningful names to the column values 
    public int Column1 { get; set; } 
    public int Column2 { get; set; } 
    public int Column3 { get; set; } 
    public int Column4 { get; set; } 

    // overriden to make re-constructing the line for the file easier 
    public override string ToString() 
    { 
     // assuming tab as the delimiter, replace with whatever you're using 
     return string.Format("{0}\t{1}\t{2}\t{3}", this.Column1, this.Column2, 
      this.Column3, this.Column4); 
    } 
} 

然後,當您在讀取值,你可以這樣做:

var entries = new List<Entry>(); 

using (var fStream = File.OpenRead(fileLocation)) 
using (var reader = new StreamReader(fStream)) 
{ 
    while (!reader.EOF) 
    { 
     var line = reader.ReadLine(); 

     // assuming tab as the delimiter, replace with whatever you're using 
     var parts = line.Split('\t'); 

     if (parts.Length != 4) 
     { 
      // whatever you need to do for error handling 
      // you could throw an error or just skip to the next line 
      continue; 
     } 

     entries.Add(
      new Entry 
      { 
       // ideally you'd use int.TryParse to provide further error handling 
       Column1 = int.Parse(parts[0]), 
       Column2 = int.Parse(parts[1]), 
       Column3 = int.Parse(parts[2]), 
       Column4 = int.Parse(parts[4]) 
      } 
     ); 
    } 
} 

然後,如果你需要只用一個列值交互時,您可以使用LINQ查詢只需要

var column1Values = from entry in entries 
        select entry.Column1; 
+0

哇,這是非常有益的,我沒有期待這麼多的幫助:)我會試試這種方式,看看我如何繼續,再次感謝您的幫助 – user2125084 2013-03-01 22:04:29

0

您正處在正確的軌道上。我個人喜歡File.ReadAllLines(@"yourTxtFile")。它讓我的代碼變得簡單。

foreach(var line in File.ReadAllLines(@"yourTxtFile")) 
{ 
    // split and add to the respective lists here 
} 
+0

我很高興在正確的軌道:)。我已經有了代碼sumular,並從這我可以添加到列表中的每一行我努力將每列添加到單獨的列表,因此list1包含列1數據等直到他們是每個數據列的4列表,如果這是有道理的遺憾其不正確的術語 – user2125084 2013-03-01 21:29:02

相關問題