What’s the translation of this snippet in VB .NET?
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, Boolean> predicate)
{
foreach (TSource element in source)
{
if (predicate(element))
yield return element;
}
}
The problem here isn’t converting an extension method – it’s converting an iterator block (the method uses
yield return. VB doesn’t have any equivalent language construct – you’d have to create your own implementation ofIEnumerable<T>which did the filtering, then return an instance of the class from the extension method.That’s exactly what the C# compiler does, but it’s hidden behind the scenes.
One point to note, which might not be obvious otherwise:
IEnumerator<T>implementsIDisposable, and aforeachloop disposes of the iterator at the end. This can be very important – so if you do create your own implementation of this (and I’d recommend that you don’t, frankly) you’ll need to callDisposeon the iterator returned fromsource.GetEnumerator()in your ownDisposemethod.