Xunrui Chow
Xunrui Chow

Reputation: 41

Cannot convert arraylist to string array

    public string[] getallTourID()
    {
        ArrayList TourIDs = new ArrayList();
        foreach (Tour o in TourCollections) //TourCollections is an arraylist of tour objects
        {
            TourIDs.Add(o.getID); //ID is a string from the tour object
        }
        return TourIDs.ToArray(typeof(string));
    }

Hi, I needed help with this issue where I cannot convert the arraylist to string array. The error says that:

Cannot implicitly convert type System.Array to string[], an explicit conversion exist

The problem comes from the ToArray() function. May I know what is the issue?

Will really appreciate the help :)

Upvotes: 1

Views: 1212

Answers (4)

Pac0
Pac0

Reputation: 23149

To solve what you want, you can simply use a simple linq query and avoid any intermediate explicit array / list :

using System.Linq;

public string[] getallTourID()
{
    return TourCollections.Select(o => o.getId).ToArray();
}

You could actually do litteraly what you want by casting the result of ToArray(typeof(string)) as string[], but the usual modern "Csharpic" way to do it is the linq projection.

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56423

I don't see why you need a raw ArrayList collection, you should be making it a List<Tour> and then extract the Id's:

as such:

return TourCollections.Select(t => t.getId).ToArray();

if for some reason you cannot do that then use OfType to only return objects from a source collection that are of a certain type.

return TourIDs.OfType<string>().ToArray();

Upvotes: 2

Irf92
Irf92

Reputation: 369

Use the following code

  TourIDs.ToArray(typeof(string)) as string[];

For further info, Refer https://www.dotnetperls.com/convert-arraylist-array

Upvotes: 0

Aria
Aria

Reputation: 3844

Try this:

Solution 1:

string[] array = TourIDs.ToArray(typeof(string)) as string[];

Solution 2:

String[] array= (String[])TourIDs.ToArray(typeof(string));

Upvotes: 2

Related Questions