2013-10-11 71 views
0

運算符'!='不能應用於類型'string []'和'字符串'的操作數 (是的,我知道類似的問題之前曾被問過,正在使用的上下文/元素是不同的類型,所以我會很感激幫助我的情況:))不等式運算符不適用於字符串數組

我有一個文件,我想停止閱讀,只要我擊中以「0」開頭的行文件。 我的while循環與不等式運算符有關。

private void button1_Click(object sender, EventArgs e) 
{ 
    // Reading/Inputing column values 

    OpenFileDialog ofd = new OpenFileDialog(); 
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    { 

     string[] lines = File.ReadAllLines(ofd.FileName).Skip(8).ToArray(); 
     textBox1.Lines = lines; 

     while (lines != "0") // PROBLEM Happens Here 
     { 

      int[] pos = new int[3] { 0, 6, 18 }; //setlen&pos to read specific colmn vals 
      int[] len = new int[3] { 6, 12, 28 }; // only doing 3 columns right now 


      foreach (string line in textBox1.Lines) 
      { 

       for (int j = 0; j < 3; j++) // 3 columns 
       { 
        val[j] = line.Substring(pos[j], len[j]).Trim(); // each column value in row add to array 
        list.Add(val[j]); // column values stored in list 

       } 

      } 

     } 
    } 
+0

與 的foreach替換,而(行= 「0」!) – CSharpie

回答

5

你得到的錯誤,因爲linesstring[]不是一個單一的string。但是你想停下來以"0"開頭的第一行。所以,你可以在foreach添加復:

foreach (string line in lines) 
{ 
    if(l.StartsWith("0")) break; 
    // ... 

不過,我會用這種方法,而不是隻得到了相關線路:

var lines = File.ReadLines(ofd.FileName).Skip(8).TakeWhile(l => !l.StartsWith("0")); 

不同的是,ReadLines不需要處理整個文件。

+0

嘿(串線lines.Where(線=>行= 「0」)!)蒂姆,偉大的職位。我只是有一個關於「l =>!l.StartsWith」的問題。這個語法看起來很有趣,尤其是l =>。無論如何,謝謝一噸! – user2788405

+0

這就是所謂的lamda表達式,通常與[Linq](http://msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx)一起使用,您可以閱讀[here](http:// msdn.microsoft.com/en-us/library/vstudio/bb397687.aspx)。除此之外,你的問題是什麼?考慮接受一個答案。 –

+0

嘿蒂姆你的方法奏效,謝謝!另一個問題。有沒有辦法在「跳過」中有多個聲明?我也可以寫.Skip(8 && l.StartsWith(「0」); – user2788405

2

string[] lines陣列和你一個string檢查它。

它應該是這樣的:

//to check if an element is an empty string 
lines[index] != "" 

//to check if the array is null 
lines != null 

//to check if the array has any elements 
lines.Count() != 0 
lines.Length != 0