獲取

2014-01-19 40 views
-1

我有以下StreamReader線通過的StreamReader的部分:獲取

using (StreamReader sr = new StreamReader("TestFile.txt")) 
{ 
    while (!sr.EndOfStream) 
    { 
     String line = sr.ReadLine(); 
     if (line != null && line.Contains(":")) 
      Console.WriteLine(line.Split(':')[1]); 
    } 
} 

我想知道如何做的是:

我怎樣才能提取此行的一部分嗎?

111033 @@的Item1 @@ 21 @@ 0 @@ 37 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 1000

我想111033,21,37,1000,並把它放在一個文本框這樣

textbox_1 = 111033 etc. 
+0

組合框行總是這樣的格式? – JaredPar

+0

是的,我得到了大約3000行SameFormat – DaRkS

回答

0

我假設在字符(@)處的廣告是將行分隔成列的分隔符。如果你需要的部分總是在同一列中,你就知道他們的索引。因此,通過在隔板分割線開始走的列你有興趣:

string[] parts = line.Split('@'); 
textBox_1 = part[0]; // 111033 
textBox_2 = part[4]; // 21 
textbox_3 = part[8]; // 37 
... 

做這些線代表什麼呢?既然我不知道,我只是以一個人的地址爲例(這裏可能不是這種情況,但這不重要)。

創建一個可以存儲對象的類。 (爲了簡單起見,我沒有包括有效性測試)。

public class Address 
{ 
    public int ID { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string City { get; set; } 

    public static Addess FromLine(string line) 
    { 
     var a = new Address(); 

     string[] parts = line.Split('@'); 

     a.ID = Int32.Parse(parts[0]); 
     a.FirstName = parts[3]; 
     a.LastName = parts[4]; 
     a.City = parts[8]; 
     return a; 
    } 

    public override string ToString() 
    { 
     return String.Format("{0} {1}, {3}", FirstName, LastName, City); 
    } 
} 

現在您可以將這些對象添加到組合框中。它們將根據ToString方法自動顯示。你可以用

Address a = (Address)myComboBox.SelectedItem; 

獲得所選擇的項目可以填補這樣

var items = new List<Address>(); 
while (!sr.EndOfStream) { 
    string line = sr.ReadLine(); 
    if (line != null && line.Contains("@")) { 
     Address a = Address.FromLine(line); 
     items.Add(a); 
    } 
} 
myComboBox.DataSource = items; 
+0

爲我工作,但不是所有的行,並沒有在同一順序我可以在組合框中輸入零件[0],並顯示整行,行開始與combobox.text? – DaRkS

+0

關鍵問題是要顯示的零件的選擇標準是什麼?他們總是處於相同的位置(在同一列中),還是總是希望顯示不是零的數字,而與他們的位置無關?請明確說明! –

+0

我想這部分的 0int,1string,4,37 0也許在組合框中,並在文本框中顯示1,4,37基於Combobox Coz i有線充滿@@很難找到任何東西 ex:5060720 @ @ @@眼鏡蛇0 @@ 0 @@ 140 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 3000 @@ 3000 @@ 0 @@ 0 @@ 0 @@ 0 @@ 0 @@ 1 @@ 1 @@ 0 @@ 0 @@ 0 @@ 601 @@ 4 @@ 0 @@ 1 @@ 0 @@ 0 @@ 1 @@ 800 @@ 0 @@ 0 @@ 1 @@ 9億@@ 0 @@ 0 @@ 1000 @@ 0 @@ 0 @@ 0 @@ 0 @@ 300 @@ 0 @@ 0 @@ 0 @@ 0 @@ @ 0 @ 0 @@ 0 @@靈魂@@文字在這裏@@ 9 @@ 6 @@ 30 @@ 0 @@ 12000 @@ 500 @@ – DaRkS

0
using (StreamReader sr = new StreamReader("TestFile.txt")) 
      { 
       while (!sr.EndOfStream) 
       { 
        String line = sr.ReadLine(); 
        if (line != null && line.Contains(":")) 
        { 
         line.Split(new [] { '@' }, StringSplitOptions.RemoveEmptyEntries) 
           .Where(x => !x.Any(c => char.IsLetter(c))) 
           .ToList() 
           .ForEach((ln) => Console.WriteLine(ln)); 

        } 
       } 
      } 

這將寫入所有號碼的console.Also你可以把它縮短這樣的:

line.Split(new [] { '@' }, StringSplitOptions.RemoveEmptyEntries) 
    .Where(x => !x.Any(char.IsLetter)) 
    .ToList() 
    .ForEach(Console.WriteLine);