So the problem is : I want to read from file and exclude certain strings( i am inexperienced so I decided to use IF so i want to exclude the strings Name, facultyNumber and etc. but it doesn't exclude them for some reason ? (I've tried to remove the spaces from the if statement)
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++;
}
The content of the file is this:
> 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
You can use Contains
like this:
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]);
}
}
}
But I think you can do it with LINQ. The code will be much cleaner:
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);
}