Pablo Gonzalez
Pablo Gonzalez

Reputation: 693

C# best way to convert object to string array

I am stuck in something. I want to convert this object, which is a array of objects, into a array of strings I cannot find a good way to do that. Do I need to use a for loop? If someone can also tell me why these 2 methods failed, I will appreciate.

    object greetings = new object[] { "hi", "hello", "greetings" };
    if (greetings.GetType().IsArray)
    {
        //string[] arr = greetings as string[];
        //string[] arr = (string[])greetings;
    }

Upvotes: 0

Views: 12890

Answers (4)

woosung cho
woosung cho

Reputation: 1

object result=new object();
.....
object[] sampleArr =(object[]) result; //change object as array

foreach(var m in sampleArr)
{
  string str = (string )m; //read out array
}

Upvotes: 0

John Wu
John Wu

Reputation: 52210

If you want to include only objects that are strings:

string[] result = greetings.OfType<string>().ToArray();

If you want to include everything (non-strings throw an exception):

string[] result = greetings.Cast<string>().ToArray();

Upvotes: 1

Insoft Nepal
Insoft Nepal

Reputation: 11

try this.

object[] objArray = { "A", "B", "C" };
string[] strArray = objArray.Cast<string>().ToArray();

//2.
object[] objArray2 = { "A", null, 1, false };
foreach (object obj in objArray2)
{
  if (obj != null)
  {
    if (obj.GetType() == typeof(string))
    {
      //strings values in here
    }
  }
}

Upvotes: -1

shingo
shingo

Reputation: 27011

string[] arr = Array.ConvertAll((object[])greetings, Convert.ToString);

Upvotes: 2

Related Questions