How Do Foreach Loops Work in C#

How does foreach loop work in c# i-e MSIL?

The foreach construction is equivalent to:

IEnumerator enumerator = myCollection.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
object current = enumerator.Current;
Console.WriteLine(current);
}
}
finally
{
IDisposable e = enumerator as IDisposable;
if (e != null)
{
e.Dispose();
}
}

Note that this version is the non generic one. The compiler can handle IEnumerator<T>.

How does foreach work when looping through function results?

The function's only called once, to return an IEnumerator<T>; after that, the MoveNext() method and the Current property are used to iterate through the results:

foreach (Foo f in GetFoos())
{
// Do stuff
}

is somewhat equivalent to:

using (IEnumerator<Foo> iterator = GetFoos().GetEnumerator())
{
while (iterator.MoveNext())
{
Foo f = iterator.Current;
// Do stuff
}
}

Note that the iterator is disposed at the end - this is particularly important for disposing resources from iterator blocks, e.g.:

public IEnumerable<string> GetLines(string file)
{
using (TextReader reader = File.OpenText(file))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}

In the above code, you really want the file to be closed when you finish iterating, and the compiler implements IDisposable cunningly to make that work.

C# foreach loop

I think you need to move the return outside the loop.

List<string> personmessages = new List<string>();
foreach (string i in messages)
{
//// Do stuff.
}
return personmessages;

In .NET, which loop runs faster, 'for' or 'foreach'?

Patrick Smacchia blogged about this last month, with the following conclusions:

  • for loops on List are a bit more than 2 times cheaper than foreach
    loops on List.
  • Looping on array is around 2 times cheaper than looping on List.
  • As a consequence, looping on array using for is 5 times cheaper
    than looping on List using foreach
    (which I believe, is what we all do).

How to use for loop instead of foreach loop?

You heard incorrectly.

for loops are not much faster than foreach loops.

In fact, for some collections, foreach loops are much faster than for loops.

ToList() is slower than either of them.

If you really want to make your code faster, you should use an O(n) LINQ join instead of the O(n2) Single() call.

How does foreach loop works with 2d array?

2D string array is not optimal choice for your task ("build a store with car"). c# is object-oriented language, so you can have a class for Car, and a class for Store with list of cars - easy to build, maintain, modify:

public class Car
{
public string Brand { get; set; }
public double Price { get; set; }
public int Year { get; set; } // new Car property
}

public class CarStore
{
public IList<Car> Cars { get; } = new List<Car>();
}

then use for loop or foreach - both will work

public static void Main()
{
var store = new CarStore
{
Cars =
{
new Car { Brand = "Ford", Year = 2021, Price = 120000 },
new Car { Brand = "Chevrolet", Year = 2020, Price = 100000 },
}
};
foreach(var car in store.Cars)
{
Console.WriteLine(car.Price.ToString("C"));
}
// new car arrived:
store.Cars.Add(new Car { Brand = "Rolls-Royce", Year = 2022, Price = 1_000_000 });
}

How do you get the index of the current iteration of a foreach loop?

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

  • MoveNext()
  • Current

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

The concept of an index is foreign to the concept of enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

C# foreach loop not executing

GetRecords returns a stateful IEnumerable the yields a single record at the time. The operative word here is stateful - once you've consumed a record (e.g., by iterating over it with a foreach loop), it's gone.

There are a few approaches you could take here:

  1. Collapse all your in to a single foreach loop instead of three different loops which perform different parts of the logic.
  2. Call GetRecords every time you need to iterate over the records. Note that this will reread the file, so you'll be performing triple the I/O.
  3. Convert the iterable to a List (e.g., by using Linq's ToList()), and then iterate over it whenever you wish. Note that this means you'll be holding the entire file's contents in memory isntead of just a small portion of it.


Related Topics



Leave a reply



Submit