Eduards Ratniks Eduards Ratniks - 13 days ago 5
C# Question

C# Check array for string

I'm Year 1 student so I don't know much about c# yet....

Is there any way to check if user inputed array contains a certain string?
If so I need to add a value to another array.

Here is the code I have so far:

var lookup = new Dictionary<string, string>
{
["H1"] = "100",
["O1"] = "56",
["H2"] = "88",
["O2"] = "46",
["H3"] = "77",
["O3"] = "37",
["H4"] = "66",
["O4"] = "28",
["H5"] = "56",
["O5"] = "20",
["H6"] = "46",
["O6"] = "12",
["H7"] = "37",
["O7"] = "0",
["H8"] = "0",
["O8"] = "0",
};

//input grades/subject
int s;
int g;
int p;

string[] grades = new string[6];
string[] subjects = new string[6];
string[] points = new string[6];

// Accepting value from user
for (s = 0, g = 0,p=0; s <= 5; s++, g++,p++)
{
Console.Write("\nEnter your subject:\t");
subjects[s] = Convert.ToString(Console.ReadLine());
subjects[s] = subjects[s].ToUpperInvariant();


Console.Write("\nEnter your grade:\t");
grades[g] = Convert.ToString(Console.ReadLine());
grades[g] = grades[g].ToUpperInvariant();
if (!lookup.TryGetValue(grades[g], out points[p]))
Console.WriteLine("Wrong Grade Format!");

}

Console.Clear();
for (s = 0, g = 0,p=0; s <= 5; s++, g++,p++)
{
Console.WriteLine("{0,15}:{1}:{2}", subjects[s], grades[g],points[p]);//output
}


I need to check array that is created by user and if there is Math then +25points has to be added

Answer

Is there any way to check if [..] array contains certain string

Yes there is. The method is called even exactly like this.
First make sure that you are using the necessary namespace:

using System.Linq;


if (subjects.Contains("MATH"))
{
    // do what ever is needed
}

ps. Consider following the advise by Jon Skeet

EDIT:

as you actually can follow the value entering process of the user step by step you could also check immediately whether the input matches your criterion:

// Accepting value from user 
for (s = 0, g = 0,p=0; s <= 5; s++, g++,p++)
{
    Console.Write("\nEnter your subject:\t");
    string input = Convert.ToString(Console.ReadLine());
    if (input.ToUpperInvariant() == "MATH")
    { /* do what ever is needed */}
    subjects[s] = input.ToUpperInvariant();

EDIT 2:

Since you increment all 3 variables in your for-loop exactly the same way, you can use only 1 variable and index every array with the same one:

for (int i = 0; i <= 5; i++)
{
    subjects[i]...
    grades[i]...
    points[i]...
}