Arvin Ashrafi
Arvin Ashrafi

Reputation: 661

C# - Only read first char with Whileloop

I have been searching for about an hour and simply can't find any solutions to this. I want each row from my .txt-file to be added to my list as long as it starts with the same number. The problem lies within "line.Substring(0, 1)" and i dont know how to solve it. Perhaps you understand what i want to acheive.

        using (StreamReader file = new StreamReader(schedulePathDays))
        {
            string line;
            while ((line.Substring(0, 1) = file.ReadLine()) == thisDay.ToString())
            {
                exercisesRow.Add(line);
            }
        }

Upvotes: 1

Views: 905

Answers (3)

cuongle
cuongle

Reputation: 75306

You can use ReadLines and then use LINQ to filter:

var result = File.ReadLines("yourPath")
                 .Where(line => line.StartsWith("1"));

ReadLines is deferred execution so it can work in large text file.

Edit: To map with your code, replace your code with below:

exercisesRow = File.ReadLines(schedulePathDays)
                   .Where(line => line.StartsWith(thisDay.ToString()))
                   .ToList();

Upvotes: 5

xen-0
xen-0

Reputation: 709

Your Substring(0,1) is in the wrong place. It should come after line is assigned.

//Altnerately: (...).Substring(0,1) instead of (...)[0]
while((line = file.ReadLine())[0] == thisDay.ToString()[0]){
    //code
}

It makes no sense to ask try to assign the result of the Substring method.

Upvotes: 0

Chris
Chris

Reputation: 27609

Your syntax doesn't make sense. You might want something like:

file.ReadLine().Substring(0,1)==thisDay.ToSTring()

I think this is what you wanted to write though Cuong Le's answer is probably a lot nicer (except needing parameterisation).

Upvotes: 0

Related Questions