开发者

Linq and streamreader getting lines

开发者 https://www.devze.com 2022-12-20 20:48 出处:网络
Using LINQ, what is an efficent way to get each string from a tab-delimited .txt file (and then get each word, usually what string.Split(...开发者_如何学编程) does)?

Using LINQ, what is an efficent way to get each string from a tab-delimited .txt file (and then get each word, usually what string.Split(...开发者_如何学编程) does)?

var v = from line in File.ReadAllLines()
   select n

Is part of this solution I believe. I don't mind if this uses yield return.

EDIT: I've also seen threads on here detailing exactly what I am trying to do, but can't find them.


I'm not entirely sure what you're asking but it sounds like you're trying to get every word from a tab delimited file as an IEnumerable<string>. If so then try the following

var query = File.ReadAllLines(somePathVariable)
                .SelectMany(x => x.Split(new char[] { '\t' });


Using File.ReadAllLines is easy - but not necessarily the most efficient, since it reads the entire line into memory.

A short version would probably be:

var wordsPerLine = from line in File.ReadAllLines(filename)
               select string.Split(line, '\t');

foreach(var line in wordsPerLine)
{
    foreach(word in line)
    {
        // process word...
    }
}

If you want a single enumerable of the words, you can use SelectMany to get that, too...

0

精彩评论

暂无评论...
验证码 换一张
取 消