user1998735
user1998735

Reputation: 253

using List and foreach

Here is my code:

  int Temp = 200;
  List<int> PrimeBuilders = new List<int>();
  PrimeBuilders.Add(200);
  PrimeBuilders.Add(300);
  PrimeBuilders.Add(400);
  PrimeBuilders.Add(500);
  PrimeBuilders.Add(200);
  PrimeBuilders.Add(600);
  PrimeBuilders.Add(400);


  foreach(int A in PrimeBuilders)
  {

  }

How can I go through the list and output the index that does not contain the number assigned to Temp?

Upvotes: 0

Views: 95

Answers (2)

Baldrick
Baldrick

Reputation: 11840

What you need is:

int Temp = 200;
var PrimeBuilders = new List<int> {200, 300, 400, 500, 200, 600, 400};

for (int i = 0; i < PrimeBuilders.Count; i++)
{
    Console.WriteLine("Current index: " + i);

    if (PrimeBuilders[i] != Temp)
    {
        Console.WriteLine("Match found at index: " + i);
    }
}

Firstly, you can initialize your list with 1 line. Secondly, if you need an index, then foreach will not give you that. You need a for loop, as shown above.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

If you need indexed you probably should go with for instead of foreach:

for(int i = 0; i < PrimeBuilders.Count; i++)
{
    if(PrimeBuilders[i] != Temp)
        Console.WriteLine(i.ToString());
}

Bonus: LINQ one-liner:

Console.WriteLine(String.Join(Environment.NewLine, PrimeBuilders.Select((x, i) => new { x, i }).Where(x => x.x != Temp).Select(x => x.i)));

Upvotes: 2

Related Questions