Can IEnumerable.Select() skip an item?

Viewed 13564

I have this function:

public IEnumerable<string> EnumPrograms() {
    return dev.AudioSessionManager2.Sessions.AsEnumerable()
        .Where(s => s.GetProcessID != 0)
        .Select(s => {
            try {
                return Process.GetProcessById((int)s.GetProcessID).ProcessName;
            }
            catch (ArgumentException) {
                return null;
            }
        });
}

The try..catch is necessary since there may be sessions with a PID that doesn't exist anymore. I'd like to skip them. Is there a way to do this from the Select callback or do I need to add a new Where condition that skips null values?

6 Answers

Building on John Skeet's post this extension method has saved me countless lines of code. The name fits perfectly SelectWhere. The code listing below is an Extension method you can use.

    public static IEnumerable<TResult> SelectWhere<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, Func<TSource, bool> predicate)
    {
        foreach (TSource item in source)
            if (predicate(item))
                yield return selector(item);
    }

Usage:

entity.SelectWhere(e => e.FirstName, e => e.Age>25);

And here is a simpler version of the extension methods by using LINQ:

public static IEnumerable<TResult> FilteredSelect<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, Func<TSource, TResult> selector)
{
    return source
        .Where(item => predicate(item))
        .Select(item => selector(item));
}
Related