C# IF 语句不排除字符串

标签 c# if-statement readfile

所以问题是:我想从文件中读取并排除某些字符串(我没有经验,所以我决定使用 IF,所以我想排除字符串 Name、failureNumber 等,但它并不排除某些字符串)原因?(我尝试删除 if 语句中的空格)

 public void read()
            {
               string[] textes = File.ReadAllLines(@"C:\Users\sashk\Source\Repos\ConsoleApp6\ConsoleApp6\save.txt", Encoding.Default);
                double[] gread = new double[] { 1, 2, 3 };
                List<string> texts = new List<string>();
                int i= 0;
                int z = 0;
                foreach (string text in textes)
                {
                    string[] words = textes[i].Split(' ');
                    for (int j = 0; j < words.Length; j++)
                    {
                        if (!words[j].Equals(" Name: ") || !words[j].Equals(" FacultyNumber: ") || !words[j].Equals(" Grades: ") || !words[j].Equals(" AverageGrade: "))
                        {
                            texts.Add(words[j]);
                        }
                    }
                    //  for (int j = 2; j < texts.Count; j++)
                    //  {
                    //      gread[z] = Convert.ToDouble(texts[j]); 
                    //  }
                    //  addStudent(texts[0], Convert.ToInt32(texts[1]), gread);
                    for (int j = 0; j < 40; j++)
                    {
                        Console.WriteLine(texts[j]);
                    }
                    i++;
                }

文件内容是这样的:

> Name: asd FacultyNumber: 2 Grades: 1,23  4,56  7,89   AverageGrade: 4,56
 Name: as FacultyNumber: 4 Grades: 1  5  9   AverageGrade: 5
 Name: ad FacultyNumber: 3 Grades: 2  4  7   AverageGrade: 4,33333333333333
 Name: ddd00 FacultyNumber: 1 Grades: 12  15  99   AverageGrade: 42

最佳答案

您可以像这样使用Contains:

var excluded = new[] { "Name:", "FacultyNumber:", "Grades:", "AverageGrade:" }; 

foreach (string text in textes) 
{
    string[] words = textes[i].Split(' ');
    for (int j = 0; j < words.Length; j++) 
    {
        if (!excluded.Contains(words[j]))
        {
            texts.Add(words[j]);
        }
    }
}

但我认为你可以使用 LINQ 来做到这一点。代码会更加简洁:

string[] textes = File.ReadAllLines(@"C:\Users\sashk\Source\Repos\ConsoleApp6\ConsoleApp6\save.txt", Encoding.Default);

var excluded = new[] { "Name:", "FacultyNumber:", "Grades:", "AverageGrade:" }; 

var texts = textes.SelectMany(x => x.Split(' ').Where(y => !excluded.Contains(y)));

foreach(string word in texts)
{
    Console.WriteLine(word);
}

关于C# IF 语句不排除字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53436324/

相关文章:

python - 为什么它说 Global Name not Defined 而不是? Python

javascript - 多重 if 条件不起作用

python - 索引错误 : single positional indexer is out-of-bounds and if condition

c# - 将文件中的数据加载并解析到数组中

java - 如何在 Spring MVC 应用程序中从我的 Tomcat 文件夹中的 bin 目录中读取文件?

c# - 如何通过脚本使 Texture2D 可读

c# - 文本区域最大长度在按下 Enter 键时不起作用

c# - SendMessage 到 .NET 控制台应用程序

c# - Discord.NET 获取特定 react 的 react 计数

react-native - 为什么react-native-fs的readFile只读取文本文件的一部分?