WebThe sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an … WebMar 6, 2010 · c# - increment a count value outside parallel.foreach scope - Stack Overflow increment a count value outside parallel.foreach scope Ask Question Asked 13 years, 1 month ago Modified 2 years, 8 months ago Viewed 32k times 30 How can I increment an integer value outside the scope of a parallel.foreach loop?
c# - ArgumentOutOfRangeException when looping with foreach and counter ...
WebSep 20, 2024 · C#’s foreach loop makes it easy to process a collection: there’s no index variable, condition, or code to update the loop variable. Instead the loop variable is … WebNow, if you want to ignore that advice and use a ForEach method anyway, it's not hard to write one that provides an index to the action: public static void ForEach (this IEnumerable sequence, Action action) { // argument null checking omitted int i = 0; foreach (T item in sequence) { action (i, item); i++; } } Share platinum construction and paving pty ltd
Counter in foreach loop in C# - Stack Overflow
Web3 Answers Sorted by: 143 Rather than using side-effects, use the overload of Select which takes an index: stuff.Select ( (value, index) => new { index, value.Name }); You could do it using side-effects, but not in the way you tried: int counter = 0; var query = from a in stuff select new { count = counter++, a.Name }; WebApr 29, 2015 · If you use a for-loop the way you do, it will iterate over the IEnumerable for each i. A good solution is a foreach loop. You can use a counter counting up each loop iteration if you need an index. Share Improve this answer Follow answered Apr 29, 2015 at 8:36 nvoigt 73.6k 26 95 140 Add a comment 1 WebNov 18, 2024 · Just write an extension method like this: using System.Linq; ... public static IEnumerable< (T item, int index)> WithIndex (this IEnumerable source) { return source.Select ( (item, index) => (item, index)); } And now you can do this: foreach (var (item, index) in collection.WithIndex ()) { DoSomething (item, index); } platinum construction