ForEach() method in .Net

Introduction:-

Why i write about this ?
 When i find this ForEach() then i thought it’s same as “foreach” loop and just skipping it but when i see that it has method symbol then bit confused and started reading about this.At last i found that both are different. The ForEach() is a method specifically designed to iterate over list or collection type of data; and this method present under List class inside base class library.

Syntax:-
public void ForEach(Action action);
When to use  ?
This is a method present under List class inside base class library; this method basically used when you working with entity framework and when you are using list to iterate over it.
How to use ?
It can only be used for the list type of data.
for eg:- List lstStudent;

It takes a delegate as parameter; where we need to pass the lambda expression and access all the list data.

Demo :-

var enrollments = new List()
{
new Enrollment { CourseId=1000, StudentId=1, grade=Grade.A },
new Enrollment { CourseId=1001,StudentId=2, grade=Grade.B },
new Enrollment {CourseId=1002, StudentId=3, grade=Grade.C },
new Enrollment {CourseId=1000, StudentId=4, grade=Grade.D },
new Enrollment {CourseId=1003, StudentId=5, grade=Grade.B },
new Enrollment {CourseId=1004, StudentId=6,grade=Grade.A },
};
enrollments.ForEach(e => context.Enrollments.Add(e));

Explanation :- Here I have enrollment list and i am adding the value inside Enrollment list by using ForEach() method.In the above ‘e’ represent lambda expression and what i am doing here is that i am iterating over this particular list enrollments and adding each value of enrollment list to my context class Enrollment list.
Context is my class where the Enrollments list present; see bellow:-

class context
{
List Enrollments;
}
If any doubt or any question regarding the above explanation feel free to ask me inside comment box.
#Share #Comment #Like
Thanks.

🙂

Advertisements

One thought on “ForEach() method in .Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s