Monday, March 25, 2013

Selecting multiple element from a List using Lambda Expression

I was searching an easy way to select multiple entry form a List of objects using Lambda Expression by matching their IDs. It can be done easily using a loop but I don't wanna use a loop in my code just for this. Finally I found it and it is very easy.

Consider you have a List of objects where each object has an field called ID. You want to extracts 5 elements from that List by matching the ID. The size of the list maybe few thousand.

Just use for following code, and you are done



List someListOfIds = new List(700, 1234, 3412, 400, 10); mainlist.Where(x => someListOfIds.Contains(x.ID));

This technique helps us to find few date from the Database by avoiding complex nested query if you don't love writing those query :)

No comments: