繁体   English   中英

C#将文件内容存储到列表<String>

[英]C# store file content to a List<String>

我想要达到的目标:

想要读取文本文件并将其存储在字符串列表中。 如果使用正则表达式,则使用第二个字符串列表进行保存

我不知道如何解决这个问题,但这是我到目前为止所做的。

using (StreamReader content = new StreamReader(@file_To_Read))
{

 List <String> newLine = new List <String> ();

 string line;
    while (line = content.ReadLine()) != null) 

 //add line to List
  newLine.Add(line);
}

可以说某些行中有名为“ causes”的文本。我现在想要的是轻松遍历列表或行,然后将行存储在新列表中。

您可以像这样过滤列表

List<string> newlist = newLine.Where(x => x.Contains("your string to match")).ToList();

您是否考虑过使用File.ReadAllLines

string[] lines = System.IO.File.ReadAllLines("your_file_path.txt");

或更多您的要求。

List<string> lines = System.IO.File.ReadAllLines("your_file_path.txt").ToList();

所以也许您想要这些东西吗?

string[] lines = File.ReadAllLines(filePath); //reads all the lines in the file into the array
string[] causes = lines.Where(line => line.ToLowerInvariant().Contains("causes")).ToArray(); //uses LINQ to filter by predicate

现在,在名为causes的数组中包含“ causes”一词的行

希望,这可以帮助您入门。

要将所有行读入列表,您可以编写以下内容:

List<string> lines = File.ReadAllLines(@file_To_Read).ToList();

现在,如果您想要一个新列表,其中包含出现“ causes”一词的所有行,则可以使用以下linq查询:

List<string> causes = lines.Where(line => line.Contains("causes").ToList();

以下应该工作

使用(StreamReader content = new StreamReader(“ FileName”)){

            List<String> newLine = new List<String>();
            while( ! content.EndOfStream)
            {
                String line = content.ReadLine();                
                if (line.Contains("causes"))
                {
                    //add line to List
                    newLine.Add(line);
                }
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM