Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# starting from second element in var

Tags:

c#

var lines = File.ReadAllLines(filelocation);
                char[] space = { ',' };
                string templine;
                foreach (string line in lines)
                {}

how do i do foreach (string line in lines[1:]) ? i want to skip the first element and start foreach from the second one

like image 752
JOE SKEET Avatar asked Dec 22 '10 22:12

JOE SKEET


1 Answers

If you are targeting .NET 3.5 or above, LINQ:

foreach (string line in lines.Skip(1)) {...}

Although it there is a lot of data, a line-reader may be better, to avoid having to hold all the lines in memory:

public static IEnumerable<string> ReadLines(string path) {
    using(var reader = File.OpenText(path)) {
        string line;
        while((line = reader.ReadLine()) != null) {
            yield return line;
        }
    }
}

then:

foreach(var line in ReadLines(filelocation).Skip(1)) {...}
like image 58
Marc Gravell Avatar answered Sep 28 '22 12:09

Marc Gravell