0

is it possible to access directly the variable i in the foreach header without using temp?

class A
{
    public int i{get; set;}
}
...
A[] many_As=new A[1000]

foreach (var element in many_As)
{
    int temp=element.i;
    ...
}
...

->

foreach (int element in many_As.i)
{
   //doing something with element
   ...
}
0

2 Answers 2

2

You can use use System.Linq:

...

using System.Linq;

...


foreach(var element in many_As.Select(x = >x.i)) 
{
    //do something
}
Sign up to request clarification or add additional context in comments.

Comments

0

Since C# 7 you can do the following:

foreach (var (value, index) in collection.Select((val, idx)=>(val, idx))) {
    Console.WriteLine($"{index + 1}th item is: {value}");
}

Here we are making use of ValueTuple and tuple deconstruction.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.