C# yield keyword

The yield keyword used in an iterator block to provide a value to the enumerator object or to signal the end of iteration.

 

public static class ProccessFilter

{

    public static IEnumerable<T> Filter<T>(this IEnumerable<T> processes, Func<T, bool> filter)

    {

        if (processes == null)

            yield break;

               

        try !Cannot yield a value in the body of a try block with a catch clause.      

 

        {

            foreach (var item in processes)

            {

                Trace.WriteLine(item);

                if (filter(item))

                    yield return item;

            }

        }

        catch(Exception ex){}

    }

}

 

class Program

{

    static void Main(string[] args)

    {

        IEnumerable<Process> t = Process.GetProcesses();

        var allProcesses = t.Filter(o => o.WorkingSet64 > 1024 * 1024 * 50);

 

 

        foreach (var item in allProcesses)

        {

            Trace.WriteLine(item.ProcessName);

            Trace.WriteLine(item.WorkingSet64);

        }

 

        Console.ReadKey();

    }

}

 

 

The yield break keyword stops enumerating and returns empty IEnumerable<T>.

 

http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s