Intelligent way of removing items from a List while enumerating in C#

The best solution is usually to use the RemoveAll() method: myList.RemoveAll(x => x.SomeProp == “SomeValue”); Or, if you need certain elements removed: MyListType[] elems = new[] { elem1, elem2 }; myList.RemoveAll(x => elems.Contains(x)); This assume that your loop is solely intended for removal purposes, of course. If you do need to additional processing, then the … Read more

Check for null in foreach loop

Just as a slight cosmetic addition to Rune’s suggestion, you could create your own extension method: public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source) { return source ?? Enumerable.Empty<T>(); } Then you can write: foreach (var header in file.Headers.OrEmptyIfNull()) { } Change the name according to taste 🙂

foreach with index [duplicate]

I keep this extension method around for this: public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action) { var i = 0; foreach (var e in ie) action(e, i++); } And use it like so: var strings = new List<string>(); strings.Each((str, n) => { // hooray }); Or to allow for break-like behaviour: public static … Read more

How do I segment the elements iterated over in a foreach loop

You can do something like this: int i = 0; foreach (var grouping in Class.Students.GroupBy(s => ++i / 20)) Console.WriteLine(“You belong to Group ” + grouping.Key.ToString()); For a similar problem I once made an extension method: public static IEnumerable<IEnumerable<T>> ToChunks<T>(this IEnumerable<T> enumerable, int chunkSize) { int itemsReturned = 0; var list = enumerable.ToList(); // Prevent … Read more

Add a delay after executing each iteration with forEach loop

What you want to achieve is totally possible with Array#forEach — although in a different way you might think of it. You can not do a thing like this: var array = [‘some’, ‘array’, ‘containing’, ‘words’]; array.forEach(function (el) { console.log(el); wait(1000); // wait 1000 milliseconds }); console.log(‘Loop finished.’); … and get the output: some array … Read more