0

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?

1
  • 1
    foreach doesn't really deal with indexes, you'd be better to use a for loop, or maintain your own counter. Commented Nov 18, 2013 at 6:02

2 Answers 2

2

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)));
Sign up to request clarification or add additional context in comments.

1 Comment

+1. Or you can combine 2 and foreach(var item in PrimeBuilders.Select((x, i) => new { x, i }))... if foreach is required.
1

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.

5 Comments

hi sir, what if i need to output the index that has the value Temp on it. How will i be able to show it? Thank you
Just change if (PrimeBuilders[i] != Temp) to if (PrimeBuilders[i] == Temp).
Sir is it possible to output the index number of the chosen values. Sorry for the noob questions sir
It should already do that. The line Console.WriteLine(i); outputs any index which matches the condition in the 'if' statement.
i mean sir for example the 0,1,2,3 and so on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.