I have a problem, I cant reverse the following List
:
foreach (List<Foo> row in Items)
{
foreach (Foo item in row.Reverse())
{
...
}
}
I always get the error:
Type void is not enumerable
Whats the problem and how to solve it?
To use the forEach() method on an array in reverse order: Use the slice() method to get a copy of the array. Use the reverse() method to reverse the copied array.
forEach statement is a C# generic statement which you can use to iterate over elements of a List.
How do you loop through an array backwards? To loop through an array backward using the forEach method, we have to reverse the array. To avoid modifying the original array, first create a copy of the array, reverse the copy, and then use forEach on it. The array copy can be done using slicing or ES6 Spread operator.
List<T>.Reverse()
is an in-place reverse, it doesn't return a new list. It changes your orininal list.
Reverses the order of the elements in the entire
List<T>
.
You need to use row.Reverse();
in your first foreach statement. Like;
foreach (List<Foo> row in Items)
{
row.Reverse();
foreach (Foo item in row)
{
//
}
}
Here is a DEMO.
If you don't want to change your orininal list, you can use Enumerable.Reverse method instead of.
Inverts the order of the elements in a sequence.
foreach (Foo item in Enumerable.Reverse(row))
{
//
}
Here is the same DEMO with using Enumerable.Reverse<T>
method.
List<T>.Reverse
doesn't return anything - it reverses the list in place.
If you want to use the LINQ version of Reverse
which returns a reversed sequence but without mutating the existing list, you could use:
foreach (IEnumerable<Foo> row in Items)
{
foreach (Foo item in row.Reverse())
{
...
}
}
Or perhaps more clearly:
foreach (List<Foo> row in Items)
{
// We want to use the LINQ to Objects non-invasive
// Reverse method, not List<T>.Reverse
foreach (Foo item in Enumerable.Reverse(row))
{
...
}
}
List<T>.Reverse()
does an in-place reverse. That means it changes your original list.
So, you would use it like this:
foreach (List<Foo> row in Items)
{
row.Reverse();
foreach (Foo item in row)
{
...
}
}
If you don't want to change your original list, you will have to call Enumerable.Reverse
explicitly:
foreach (List<Foo> row in Items)
{
foreach (Foo item in Enumerable.Reverse(row))
{
...
}
}
The reason for not being able to use Enumerable.Reverse
in the extension method syntax is: Extension methods don't hide / override instance methods and List<T>
happens to already have a Reverse
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With