使用Linq读取文件 [英] Read a file using Linq

查看:56
本文介绍了使用Linq读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨:)



我尝试使用Linq读取一个简单的TXT文件,但是,我的困难是。读取2行2行的文件,为此,我做了一个简单的功能,但是,我相信我可以读取TXT分离2行2行...



我阅读文字行的代码是:



Hi :)

I try to read a simple TXT file using Linq, but, my dificult is. read a file in 2 by 2 lines, for this, I made a simple function, but, I belive I can read the TXT separating 2 by 2 lines...

My code to read the text lines is:

private struct Test
{
    public string Line1, Line2;
};

static List<Test> teste_func(string[] args)
{
    List<Test> exemplo = new List<Test>();
    var lines = File.ReadAllLines(args[0]).Where(x => x.StartsWith("1") || x.StartsWith("7")).ToArray();

    for(int i=0;i<lines.Length;i++)
    {
        Test aux = new Test();
        aux.Line1 = lines[i];
        i+=1;
        aux.Line2 = lines[i];

        exemplo.Add(aux);
    }

    return exemplo;
}





在创建此功能之前,我尝试这样做:





Before I create this function, I tried to do this:

var lines = File.ReadAllLines(args[0]). .Where(x=>x.StartsWith("1") || x.StartsWith("7")).Select(x =>
                new Test
                {
                    Line1 = x.Substring(0, 10),
                    Line2 = x.Substring(0, 10)
                });





但很明显,该系统将逐行获取并为该行创建一个新结构...

那么,我如何使用linq获得2行2行?



But, it's obvious, that system will be get line by line and create a new struct for the line...
So, how I can make to get 2 by 2 lines with linq ?

推荐答案

当我看你的代码时,我看到了这个:



在第一个例子中:



0.创建数组的Linq选择函数看起来没问题。



1.你并没有真正用Linq读取文件;你正在使用Linq根据标准选择读取文件的行。



2.你正在增加'for循环计数器里面 'for loop block的范围:这通常是导致灾难的东西。



当然,很容易通过以下方式处理: for(int i = 0; i< lines.Length; i + = 2){}



3.您的代码表明每次找到匹配时文件中的下一行将包含另一个匹配:这个假设是正确的吗?



那么,你的代码现在适合你吗?如果不是,你看到了什么问题?你在非常大的文件上使用它吗?
As I look at your code, I see this:

in the first example:

0. your Linq selection function that creates an array looks okay.

1. you are not really "reading" the file with Linq; you are using Linq to select lines of the read file based on criteria.

2. you are incrementing the 'for loop counter inside the scope of the 'for loop block: this is usually something that leads to disaster.

Of course, that's easily taken care of by: for (int i = 0; i < lines.Length; i += 2) {}

3. your code suggests that every time you find a match the next line in the file will contain another match: is this assumption correct ?

So, is your code working for you now ? If it isn't, what problems do you see ? Are you using this on very large files ?


引用:

那么,我怎么能得到使用linq 2乘2行?

So, how I can make to get 2 by 2 lines with linq ?



我强烈建议您继续使用非LINQ代码,因为以后更容易理解和更改(如果需要)。然而,要做出比尔伍德拉夫建议的更改。



说到这一点,看看你可以强迫LINQ实现什么是很有趣的:0即使结果代码是一个阅读和维护的噩梦:〜。



以下是在LINQ中实现此目的的两种方法。


I strongly urge you to stay with your non-LINQ code as it will be much easier to understand and change (if needed) later on. Do however, make the changes that Bill Woodruff has suggested.

With that said, it can be fun to see what you can force LINQ to achieve :0 even if the resulting code is a nightmare to read and maintain:~.

Here are two ways that came to mind to achieve this in LINQ.

// lines is used to simulate ReadAllLines function result
string[] lines = {"1 abc","2 abc","7 abc","7 efd","4 mno","1 xyz","7 nope"};

string[] filteredlines = lines.Where((string x) => x.StartsWith("1") || x.StartsWith("7")).ToArray();

List<test> BadIdea;
// note: (index & 1) == 0) is a way to check if index is an even number
//        index is the LINQ enumerator index
BadIdea = filteredlines.Where((string dummy, Int32 index) => (((index & 1) == 0) && (index <= (filteredlines.Length / 2)) && (filteredlines.Length > 1))).
                        Select((string dummy, Int32 index) => 
                        new Test {Line1 = filteredlines[index * 2],	Line2 = filteredlines[(index * 2) + 1]}).ToList();


List<test> ReallyBadIdea = default(List<test>);

// to get it all into one LINQ statement
// I use a dummy integer array with one element to enumerate over
// the temp variable tmpFilteredLines pulls in the lines to enumerate over
// as above, lines() replaces ReadAllLines function

ReallyBadIdea = (List<test>)(from dummyvar in new Int32[] {1}
                             let tmpFilteredLines = lines.Where((string x) => x.StartsWith("1") || x.StartsWith("7")).ToArray()
                             select (tmpFilteredLines.Where((string dummy, Int32 index) => 
                                 (((index & 1) == 0) && (index <= (tmpFilteredLines.Length / 2)) && (tmpFilteredLines.Length > 1))).
                             Select((string dummy, Int32 index) => new Test() { Line1 = tmpFilteredLines[index * 2], Line2 = tmpFilteredLines[(index * 2) + 1] }).ToList())).ToList()[0];
</test></test></test></test>


访问这里...



使用LINQ读取XML [ ^ ]
visit here...

Reading XML using LINQ[^]


这篇关于使用Linq读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆