Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

Is it possible foreach with outside declared variable

Usually for each writes like this

List<int> intList = new List<int>();
foreach(int a in intList)
{
  if(a > 5){
     break;
  }
}

Is it possible to do something like this

List<int> intList = new List<int>();
int a=0;
foreach(a in intList)
{
  if(a > 5){
     break;
  }
}
//do something to **a** here

Upvotes: 0

Views: 60

Answers (3)

BhushanK
BhushanK

Reputation: 1243

Else you can do this....

       List<int> intList = new List<int>();
        int a=0;
        foreach(int b in intList)
        {
          if(b > 5){
             a = b;
             break;
          }
        }
        //do something to **a** here

Upvotes: 0

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

If what you are trying to do is to find the first value in your list that's greater than 5, then something like this would be less code, and cleaner:

 int a = intList.Find(x => x > 5);

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

No, it's not possible. Following C# spec, here is the foreach loop syntax:

foreach-statement:
foreach   (   local-variable-type   identifier   in   expression   )
    embedded-statement

As you can see, local-variable-type is part of the grammar here, so it's required in the code to make it a correct C# code.

You should use LINQ and FirstOrDefault to get similar behavior in much cleaner way:

List<int> intList = new List<int>();
int a = intList.FirstOrDefault(x => x > 5)

The difference is, if you don't find an item matching the condition in your list, a will be set to default(int), not the value of last item in your collection.

Upvotes: 6

Related Questions