public class Product
{
public string Category{get;set;}
public string Name { get; set; }
public decimal Price { get; set; }
}
public class Products:IEnumerable
{
public List _products;
public Products()
{
_products = new List();
}
public void Add(Product p)
{
_products.Add(p);
}
public decimal TotalPrice(Predicate match)
{
if (match==null)
throw new ArgumentNullException();
decimal totalPrice = 0;
int itemCount = _products.Count;
for (int i = 0; i < itemCount; i++)
{
if (match(_products[i]) == true)
totalPrice += _products[i].Price;
}
return totalPrice;
}
public void ForEach(Action action)
{
for (int i = 0; i < _products.Count; i++)
{
action(_products[i]);
}
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
this._products.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
this.GetEnumerator();
}
#endregion
}
extensions:
public static class MyExtensions
{
public static int MyCount(this IEnumerable list)
{
return list.Count()/2;
}
}
tests:
[TestFixture]
public class PredicateLamdaActionTests
{
[Test]
public void TestNUnit()
{
//Assert.Fail();
Assert.That(true);
}
[Test]
public void FindPriceTest()
{
Products products = new Products();
products.Add(new Product() { Name = "Pear", Category = "fruit", Price = 2 });
products.Add(new Product() { Name = "Apple", Category = "fruit", Price = 3 });
products.Add(new Product() { Name = "Banana", Category = "berry", Price = 2 });
products.Add(new Product() { Name = "Blueberry", Category = "berry", Price = 2 });
products.Add(new Product() { Name = "Beans", Category = "vegetable", Price = 2 });
Assert.AreEqual(5,products.TotalPrice(p => p.Category == "fruit"));
}
[Test]
public void DoWorkOnAllTest()
{
Products products = new Products();
products.Add(new Product() { Name = "Pear", Category = "fruit", Price = 2 });
products.Add(new Product() { Name = "Apple", Category = "fruit", Price = 3 });
products.Add(new Product() { Name = "Banana", Category = "berry", Price = 2 });
products.Add(new Product() { Name = "Blueberry", Category = "berry", Price = 2 });
products.Add(new Product() { Name = "Beans", Category = "vegetable", Price = 2 });
//products.ForEach( delegate(Product p){p.Category="fruit";});
products.ForEach(p=>p.Category="fruit");
Assert.AreEqual(11, products.TotalPrice(p => p.Category == "fruit"));
}
[Test]
public void MyCountTest()
{
Products products = new Products();
products.Add(new Product() { Name = "Pear", Category = "fruit", Price = 2 });
products.Add(new Product() { Name = "Apple", Category = "fruit", Price = 3 });
products.Add(new Product() { Name = "Banana", Category = "berry", Price = 2 });
products.Add(new Product() { Name = "Blueberry", Category = "berry", Price = 2 });
products.Add(new Product() { Name = "Beans", Category = "vegetable", Price = 2 });
Assert.AreEqual(2, products._products.MyCount());
}
}