سؤال

Operator '!=' cannot be applied to operands of type 'string[]' and 'string' (Yes I know similar questions have been asked before, I looked at one but the context/ elements being used were of different type so I'd appreciate help with my case :) )

I have a file and I want to stop reading as soon as I hit a line which starts with "0" in the file. My while loop is having issues with the inequality operator.

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

                }

            }

        }
    }
هل كانت مفيدة؟

المحلول

You get the error because lines is a string[] not a single string. But you want to stop on the first line that starts with "0" anyway. So you could add the check in the foreach:

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

However, i would use this method instead to get only the relevant lines:

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

the difference is that ReadLines does not need to process the whole file.

نصائح أخرى

string[] lines is an array and you are checking it with a string.

It should be something like:

//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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top