Using C# Yield

I just found something cool I haven’t been using in Linq so I thought I would share here.

When enumerating through a collection of IEnumerable<Object>, you can use the yeild statement to quickly filter items.

For example if I had a set of ShoppingCartItems held in an IEnumerable<ShoppingCartItem>, and ShoppingCartItem has a Category, I could filter with an extension method like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ShoppingCartExample
{
    public interface IShoppingCartItem
    {
        string Description { get; set; }
        double Cost { get; set; }
        string Category { get; set; }
    }

    public class ShoppingCartItem : IShoppingCartItem
    {
        public string Description { get; set; }
        public double Cost { get; set; }
        public string Category { get; set; }
    }

    public static class Extensions
    {

public static IEnumerable<IShoppingCartItem> Filter(this IEnumerable<IShoppingCartItem> instance, string Category)
        {
            foreach (IShoppingCartItem item in instance)
            {
                if (item.Category == Category)
                {
                    yield return item;
                }
            }
        }

    }

}

So to use this, we ensure we’ve got the Extensions class in scope / included then call Filter on it like this:

// declare a cart
List cart = new List();

// add items
cart.Add(new ShoppingCartItem() { Category = "Toys", Cost = 1.23D, Description = "Monopoly" });
cart.Add(new ShoppingCartItem() { Category = "Fruit", Cost = 0.50D, Description = "Apple" });

// filter the items
IEnumerable results = cart.Filter("Fruit");

int count = results.Count; // will return 1

Related Content