Iterate two lists using linq, how to convert a for loop to linq method group

Some times we need to compare two lists using either for or foreach loop to check 'i' th position of list1 has same value in 'i' th positon list2. Some times we need to loop to write a single line of code. Example:- to get all files in a directory and need to delete the files.


In some situations you may need to compare two lists whether they are holding equal values at same position or not?

Our eariler apporach was

List list1 = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List list2 = new List { 1, 2, 4, 5, 6, 7, 8, 9, 10 };
// How to compare the above two lists whether the 'i' element in list1 is present in 'i' position of list2
List ElementsNotFoundinList1 = new List();
for (int i = 0; i < list1.Count; i++)
if (list1[i] != list2[i])

With linq we can use the above in to a single line of code
Note:- to use the belove line you should add System.Linq to your namespace

var ElementsNotFoundinList1 = list1.Where((t, i) => t != list2[i]).ToList();

It's pretty easy and we can avoid for loop

Important point to remember before using the above linq 'lambda expression'

1) Before using the above linq lambda expression both list should contain same size.

Note:- If you want to get the list2 objects interchange the list1 with list2 and list2 with list1

Article # 2

Some situation we need to loop a list to write a single line of code.
Example getting all files from a path and need to delete the files.
For that we normally use the below apporach

List files = Directory.GetFiles(filePath).ToList();
for (int i = 0; i < files.Count;i++ )

But the same we can write using linq like

files.ForEach(p=> File.Delete(p));

the above linq expression declares a variable called 'p' and assign the value to the 'p' which we can even make even simplier like below.


we call the above statement as 'method group'



No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: