Click here to Skip to main content
15,908,254 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am attempting this question - Return a List containing all the elements in the given array as strings, prepended by the string "element x : ". . , where x = the index of the element. I always feel as if I am close to the right code, but the concept of arrays, lists and collections is something I am still gradually becoming accustomed to. Regarding the question in the title, I have attempted to answer it using a for loop, but what would go inside the curly braces?

I keep getting errors like " "this type of thing" cannot be converted to "this type of thing" ", if you know what I mean. I'd like to understand how to get around that hurdle.

Kind regards

What I have tried:

public static List<string> RetrunModifiedList(DateTime[] anArray)
       {
           for (int i = 0; i < anArray.Length; i++)
               {
             anArray[i] = i.ToString().Prepend("element" i);
               }
           return anArray;

       }
Posted
Updated 17-Jul-17 0:08am

You have declared the input parameter anArray as being an array containing DateTime objects - but inside the loop you attempt to fill it with strings. You can't do that: that's like having a frame of round holes, and trying to fit square pegs into them!

To return strings, you must create a new collection that holds strings, and transfer the DateTime objects - as strings - into it.
The way I would do it - at least as a beginner - would be like this:
public static List<string> RetrunModifiedList(DateTime[] anArray)
   {
   List<string> results = new List<string>();
   for (int i = 0; i < anArray.Length; i++)
      {
      results.Add(string.Format("Element {0} : {1}", i, anArray[i]));
      }
   return results;
   }
 
Share this answer
 
Comments
Member 13302374 17-Jul-17 6:44am    
Thanks, let me break this down to understand it even more.
Hi,

After seeing the code snippet, I can see you are updating DateTime[] to string array.

Could you please declare separate variable for this.

eg.g

List<string> listArray= new List<string>();

And inside for loop

listArray.Add(i.ToString().Prepend("element" i));

and return listArray object.

Try this.


public static List<string> RetrunModifiedList(DateTime[] anArray)
       {
             List<string> listArray= new List<string>();

           for (int i = 0; i < anArray.Length; i++)
               {
            listArray.Add(i.ToString().Prepend("element" i));
               }
           return listArray;

       }
 
Share this answer
 
v3
Comments
Member 13302374 17-Jul-17 5:35am    
I tried this and I get errors
sputcha 17-Jul-17 8:02am    
Could you please post the error and whole code ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900