[Solved] IF Statement: Determine what was chosen. C# [closed]


If this is the original code:

foreach(string x in lines) {
   if(x.Contains("stringtofind")) {
      Console.WriteLine("Found stringtofind at line x");
   if(x.Contains("stringtofind2")) {
      Console.WriteLine("Found stringtofind2 at line x");
   ...
}

we can see that there are a pattern that is inside the foreach loop.
In order to remove the duplicated code we can put all the stringsToFind inside an array.

Like;

var lines = new string[]
{
    "line1  stringToFind1 stringToFind2",
    "line2 ",
    "line3 stringToFind3",
    "line4 stringToFind4 stringToFind5",
};

var stringsToFind = new string[]
{
    "stringToFind1",
    "stringToFind2",
    "stringToFind3",
    "stringToFind4",
    "stringToFind5",
};

foreach (string line in lines)
{
    foreach (string stringToFind in stringsToFind)
    {
        if (line.Contains(stringToFind))
        {
            Console.WriteLine(string.Format("Found {0} at line {1}", stringToFind, line));
        }
    }
}

Now, if you want to print the number of the line instead of the line, you can a.- use a counter, b.- use a for instead of the first foreach.

for (int i = 0; i < lines.Length; i++)
{
    foreach (string stringToFind in stringsToFind)
    {
        if (lines[i].Contains(stringToFind))
        {
            // We use i+1 for line number to show that in a 'human' format.
            Console.WriteLine(string.Format("Found {0} at line {1}", stringToFind, (i+1)));
        }
    }
}

solved IF Statement: Determine what was chosen. C# [closed]