var repository = new CustomerRepository();Where Customers is of type Collection. Well you can't out of the box as the framework doesn't provide an extension for IEnumerable foreach (which is what Collection implements).
repository.Customers.ForEach(customer => Console.WriteLine(string.Format("Customer: {0} {1}",
customer.FirstName, customer.LastName)));
Console.Read();
The Repository and domain object in the above case looks like this:
public class CustomerRepositoryYou can make the above call work with this simple extension for IEnumerable:
{
public CustomerRepository()
{
Customers = new Collection<Customer>()
{
new Customer()
{
FirstName = "Simon",
LastName = "Hart"
},
new Customer()
{
FirstName = "Joe",
LastName = "Bloggs"
}
};
}
public ICollection<Customer> Customers
{
get; set;
}
}
public class Customer
{
public string FirstName
{
get; set;
}
public string LastName
{
get; set;
}
}
public static class GenericIEnumerableExtensionsIt's quite simple in that it accepts one parameter, an Action delegate with one parameter - this could be extended to do whatever you want. Although the above is in line with the List.ForEach extension method.
{
public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
foreach (var item in collection)
{
action(item);
}
}
}
The benefit of this is it simply reads better with less code.
You might find this library found on codeplex useful: http://extensionmethodsyay.codeplex.com/