My code posted below, does not run, due to an
Error - Cannot implicitly convert type 'string' to 'int'
This error occurs to the iterator i within both my if conditions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MaleOrFemale
{
class Program
{
static void Main(string[] args)
{
string[,] names = new string [7,2] {{"Cheryl Cole","F"},{"Hilary Clinton","F"},{"Noel Gallagher","M"},{"David Cameron","M"},{"Madonna","F"},{"Sergio Aguero","M"},{"Sheik Mansour","M"}};
int mCount = 0;
int fCount = 0;
foreach ( var i in names)
{
if (names[i,1]== "M")
{
mCount += 1;
}
else if (names[i,1]=="F")
{
fCount += 1;
}
}
Console.WriteLine("mCount = {0}", mCount);
Console.WriteLine("fCount = {0}", fCount);
Console.Read();
}
}
}
Why can my array index not use the foreach Iterator in this case?
You are trying to access the array via indexes, indexes are meant to be integers.
Here when you call
names[i,1], thenishould be integer not string. When you haveforeach ( var i in names)theniis inferred to be string because name is array of typestring[,].If you want to access each element via index try using a
forloop insteadKeep in mind that when you use
foreachyou are accessing elements not the indexes.But best way here is to define a class instead of holding data into multi-dimensional arrays.
and the program will looks like this
or you can use linq for the whole concept of counting items with specific conditions