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.
Hi,
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
List
// How to compare the above two lists whether the 'i' element in list1 is present in 'i' position of list2
List
for (int i = 0; i < list1.Count; i++)
{
if (list1[i] != list2[i])
ElementsNotFoundinList1.Add(list1[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
for (int i = 0; i < files.Count;i++ )
{
File.Delete(files[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.
files.ForEach(File.Delete)
we call the above statement as 'method group'
Regards,
Praveen