Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the actual use of Array.ConvertAll compared to e.g. looping through the array via foreach?

My question is rather generally phrased, therefore, I will not provide any code (unless someone wants me to add it, but I think my question is clear enough). I have been looking at two articles now about the Array.ConvertAll method and cannot for myself find a direct use of it. The articles I read:

http://msdn.microsoft.com/en-us/library/exc45z53.aspx

"Converter" (Bottom of article): http://www.codeproject.com/Articles/117611/Delegates-in-C-Attempt-to-look-inside-Part-4

Now I understand how the converter works and how it can be used, however, I don't see the direct necessity of it. Since the actual method of how one object is to be converted into the other, has to be fully determined (e.g. in the codeproject link the method "ConvertToPersonInfo" or the arroding Action/Lambda type delegate), is it not just possible to declare and instantiate the new array of the new objects and do a foreach-loop over the old array of the old objects and copy the desired variables within that loop?

According to the Microsoft article, the old array is not effected in any way, so the final effect will not be different.

Am I missing a point here and didn't understand the Converter, or is it really just the same?

like image 285
philkark Avatar asked Oct 18 '12 22:10

philkark


2 Answers

Of course you can do it yourself. It's just a method that simplifies the conversion by creating the array and doing the looping for you.

For example:

 int[] newArr = new int[oldArr.Length];
 for (int i = 0; i < oldArr.Length; i++) {
   newArr[i] = Convert.ToInt32(oldArr[i]);
 }

vs. just:

 int[] newArr = Array.ConvertAll(oldArr, Convert.ToInt32);
like image 130
Guffa Avatar answered Sep 19 '22 22:09

Guffa


The end result is less typed code and a very clear statement of what you're doing. I am converting this collection to that collection (and I know that by just reading the method name) instead of having to inspect the body of a foreach loop to see what's going on.

like image 20
Jim D'Angelo Avatar answered Sep 21 '22 22:09

Jim D'Angelo