List.ForEach Method
The Generic List<T> provides a very useful method called ForEach. The purpose of ForEach is to take action on every item contained in the list. In the code below I am adding the questions to the exam using the old method without using the ForEach method.
Exam exam = FakeExamRepository.GetExam();
List<Question> questions = FakeQuestionRepository.GetQuestions();
foreach (Question q in questions)
{
exam.AddQuestion(q);
}
I know that is a lot of code just to add questions to the exam. Now, let's see the same scenario using the ForEach approach.
Exam exam = FakeExamRepository.GetExam();
List<Question> questions = FakeQuestionRepository.GetQuestions();
questions.ForEach(delegate(Question question) { exam.AddQuestion(question); });
Everything performed in a single line. I hope you find this useful in your projects.
Comment Notification
If you would like to receive an email when updates are made to this post, please register here
Subscribe to this post's comments using