Hi is possible to cast List of objects to List of string array?

Recommended Answers

All 3 Replies

Yes. What do you want to be in the strings though - one specific property of the objects, or there ToString representation?

Here are some examples:

void Main()
{
    List<Person> people = new List<Person>
    {
        new Person { Firstname = "Dave", Surname = "Amour", Age = 48 },
        new Person { Firstname = "Fred", Surname = "Smith", Age = 21 },
        new Person { Firstname = "Sarah", Surname = "Greene", Age = 34 },
        new Person { Firstname = "Louise", Surname = "Atkins", Age = 41 }
    };

    var stringArrayOfFirstnames = people.Select(p => p.Firstname).ToArray();
    var stringArrayOfSurnames = people.Select(p => p.Surname).ToArray();
    var stringArrayOfFullnames = people.Select(p => p.Firstname + " " + p.Surname).ToArray();

    var stringArrayOfToString = people.Select(p => p.ToString()).ToArray();
}

public class Person
{
    public string Firstname { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return Firstname + " " + Surname + "(Aged " + Age + ")";
    }
}

What list of objects do you have?
Is it a list of all the same object, as Dave suggests or doesyour list contains different objects?

List<string> MyList = ObjectList.Select(x=>x.ToString()).ToList()

or

string [] MyArray = ObjectList.Select(x=>x.ToString()).ToArray()

Of course this all depends what the objects are in the List, this will work fine for basic types like integers, booleans, ext. But thinks like Form Components, if they don't have a specific .ToString(), you might get like a namespace value (or something like that)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.