Welcome to AspAdvice Sign in | Join | Help

AzamSharp

Some day I will know everything I hope that day never comes

Syndication

Tags

Navigation

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.

Published Monday, September 10, 2007 12:13 AM by azamsharp

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 RSS

Comments

# re: List.ForEach Method @ Thursday, September 13, 2007 12:39 PM

Or with C# 3.0: questions.ForEach(question => exam.AddQuestion(question));

Troy DeMonbreun

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below