2013-01-31 72 views
0

我有一個foreach循環數組:與陣列循環工作

StreamReader reader = new StreamReader(Txt_OrigemPath.Text); 
reader.ReadLine().Skip(1); 
string conteudo = reader.ReadLine();    
string[] teste = conteudo.Split(new[] { '*' }, StringSplitOptions.RemoveEmptyEntries); 

foreach (string s in teste) 
{ 
    string oi = s; 
} 

行我讀包含像matriculation, id, id_dependent, birthday ... 幾場我有,用戶可以選擇他想要選擇至極字段CheckedListBox以及他想要什麼樣的順序,根據這個選擇並且知道陣列中每個值的順序(我知道第一個是matriculation第二個是id而第三個是name),我怎麼能選擇一些字段,通過它值給某些變量,並根據checkedlistbox的順序對它們進行排序?希望我能清楚。

我嘗試這樣做:

using (var reader = new StreamReader(Txt_OrigemPath.Text)) 
      { 
       var campos = new List<Campos>(); 
       reader.ReadLine(); 
       while (!reader.EndOfStream) 
       { 
        string conteudo = reader.ReadLine(); 
        string[] array = conteudo.Split(new[] { '*' }, StringSplitOptions.RemoveEmptyEntries); 
        var campo = new Campos 
        { 
         numero_carteira = array[0] 
        }; 
        campos.Add(campo); 
       } 
      } 

現在,我如何可以運行在列表中,並從checkedlistbox用戶選擇那些字段比較它的價值? 因爲如果我再比如類出{}它的價值將是空的......

Person p = new Person(); 
string hi = p.numero_carteira; // null..... 
+0

你覺得'reader.ReadLine()。Skip(1);'是嗎?因爲它確實讓人煩惱。 – antonijn

+0

你想要完成什麼? – MUG4N

+0

不,根本不清楚。我得到你想要顯示來自文件的項目,並且你有一個checkedlistbox來選擇和訂購這些項目。由於您擁有列表中的項目,因此只需將列表中的項目與checkedlistbox中的項目進行比較,然後創建一個新列表,並按照正確的順序選擇項目,然後將該數據放入您的輸出中(ListView ?) –

回答

1

Skip(1)將跳過第一線的通過reader.ReadLine()返回的字符串的第一個字符。由於reader.ReadLine()本身跳過第一行,因此Skip(1)是完全多餘的。

首先創建可以存儲你的領域

public class Person 
{ 
    public string Matriculation { get; set; } 
    public string ID { get; set; } 
    public string IDDependent { get; set; } 
    public string Birthday { get; set; } 

    public override string ToString() 
    { 
     return String.Format("{0} {1} ({2})", ID, Matriculation, Birthday); 
    } 
} 

類(在這裏我使用的字符串爲簡單起見,但你可以使用整數和DateTime是否爲好,這需要一些轉換。)

現在,創建人員將被存儲的列表

var persons = new List<Person>(); 

將條目添加到此列表中。做不是拆分字符串時刪除空條目,否則你將失去你的字段的位置!

using (var reader = new StreamReader(Txt_OrigemPath.Text)) { 
    reader.ReadLine(); // Skip first line (if this is what you want to do). 
    while (!reader.EndOfStream) { 
     string conteudo = reader.ReadLine(); 
     string[] teste = conteudo.Split('*'); 
     var person = new Person { 
      Matriculation = teste[0], 
      ID = teste[1], 
      IDDependent = teste[2], 
      Birthday = teste[3] 
     }; 
     persons.Add(person); 
    } 
} 

using語句確保完成當StreamReader關閉。

+0

@ OliverJacot-Descombes我不想刪除空條目,因爲如果我的空條目是用戶想要的某個字段,我會替換其他字段的''「',你知道嗎?我現在試試 – Ghaleon

+0

Oliver它說'無效表達式'字符串爲什麼? – Ghaleon

+0

@Ghaleon:我直接在StackOverflow答案框中鍵入代碼,而不用在Visual Studio中測試它。在Visual Studio中,我發現了兩個錯誤。 #1:在「使用」行末尾缺少一個「)」。#2:不應該在'Matriculation = teste [0]'中讀取'string [xy]',而是'teste [xy]''等等。修復了答案。你使用了字符串拆分選項'StringSplitOptions.RemoveEmptyEntries';因此我說你想刪除空的條目。 –