Skip to main content
 首页 » 编程设计

c#之如何使用 C# 读取和过滤文本文件中的行

2024年02月23日17jillzhang

1) 我在下面有一个这样的文本文件。

Dilantha 
code 65 
po Bo 1255 
colombo 
sri lanka 
 
joy 
code 78 
toronto 
Canada 

2) 但我想要下面的结果。 (我不想要 code 65 和 code 78 部分)

Dilantha  colombo     sri lanka 
 
joy       toronto     Canada 

3)我的要求是,首先我要读取文本文件,然后我要过滤上面2中显示的结果。

这是我的代码。我正在使用 C#

    String line; 
    String path = "c:/sample.txt"; 
 
    StreamReader sr = new StreamReader(path); 
    while ((line = sr.ReadLine()) != null) 
    { 
        //display the readed lines in the text box 
        disTextBox.AppendText(line+Environment.NewLine); 
    } 

请您参考如下方法:

创建一个函数来返回一组字符串列表,然后创建一个类来保存这些值怎么样?

public static List<string> ReadGroup(TextReader tr) 
{ 
    string line = tr.ReadLine(); 
    List<string> lines = new List<string>(); 
    while (line != null && line.Length > 0) 
    { 
        lines.Add(line); 
    } 
 
    // change this to line == null if you have groups with no lines 
    if (lines.Count == 0)  
    { 
        return null; 
    } 
 
    return lines; 
} 

然后您可以通过列表中的索引访问行:

String line; 
String path = "c:/sample.txt"; 
 
using (StreamReader sr = new StreamReader(path)) 
{ 
    while ((List<string> lines = ReadGroup(sr)) != null) 
    { 
        // you might want to check for lines.Count >= 4 if you will 
        // have groups with fewer lines to provide a better error 
 
        //display the readed lines in the text box 
        disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}", 
            lines[0], lines[2], lines[3], Environment.NewLine); 
    } 
    sr.Close(); 
} 

我注意到您的第一个多了一行“po Bo 1255”。您需要知道您的文件是什么格式才能做任何有意义的事情。如果一组的最后两行是城市和国家,则需要使用行数。有一个类:

class LineGroup // name whatever the data contains 
{ 
    public string Name { get; set; } 
    public string Code { get; set; } 
    public string City { get; set; } 
    public string Country { get; set; } 
 
    public LineGroup(List<string> lines) 
    { 
        if (lines == null || lines.Count < 4) 
        { 
            throw new ApplicationException("LineGroup file format error: Each group must have at least 4 lines"); 
        } 
 
        Name = lines[0]; 
        Code = lines[1]; 
        City = lines[lines.Count - 2]; 
        Country = lines[lines.Count - 1]; 
    } 
} 

并处理:

while ((List<string> lines = ReadGroup(sr) != null) 
{ 
    LineGroup group = new LineGroup(lines); 
 
    //display the readed lines in the text box 
    disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}", 
        group.Name, group.City, group.Country, Environment.NewLine); 
}