Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
DotNETFrameworkNotesForProfessionals.pdf
Скачиваний:
32
Добавлен:
20.05.2023
Размер:
1.82 Mб
Скачать

Chapter 9: ForEach

Section 9.1: Extension method for IEnumerable

ForEach() is defined on the List<T> class, but not on IQueryable<T> or IEnumerable<T>. You have two choices in those cases:

ToList first

The enumeration (or query) will be evaluated, copying the results into a new list or calling the database. The method is then called on each item.

IEnumerable<Customer> customers = new List<Customer>();

customers.ToList().ForEach(c => c.SendEmail());

This method has obvious memory usage overhead, as an intermediate list is created.

Extension method

Write an extension method:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)

{

foreach(T item in enumeration)

{

action(item);

}

}

Use:

IEnumerable<Customer> customers = new List<Customer>(); customers.ForEach(c => c.SendEmail());

Caution: The Framework's LINQ methods have been designed with the intention of being pure, which means they do not produce side e ects. The ForEach method's only purpose is to produce side e ects, and deviates from the other methods in this aspect. You may consider just using a plain foreach loop instead.

Section 9.2: Calling a method on an object in a list

public class Customer { public void SendEmail()

{

// Sending email code here

}

}

List<Customer> customers = new List<Customer>();

customers.Add(new Customer()); customers.Add(new Customer());

customers.ForEach(c => c.SendEmail());

GoalKicker.com – .NET Framework Notes for Professionals

46