Filtering enumerables 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
For example if I had a set of ShoppingCartItems held in an IEnumerable
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 static class Filters
{
public static IEnumerable<IShoppingCartItem> Filter(this IEnumerable<IShoppingCartItem> instance string Category)
{
foreach (IShoppingCartItem item in instance)
{
if (item.Category == Category)
{
yield return item;
}
}
}
}
}
Example usage:
// 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 - not yet evaluated
IEnumerable results = Filters.Filter("Fruit");
// all items will be yielded during enumeration here
int count = results.Count; // will return 1