Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert Object[] to String[] or List<String>

I have a Data Row. I can get the items in it using the property dataRow.ItemArray which is of type object[]. I need to convert this to String[] or List<String>

I see the methods ToArray<> and ToList<>. but dont know how to use it.Kindly help.

Thanks in Advance

like image 942
Ananth Avatar asked Feb 22 '11 18:02

Ananth


People also ask

How do you turn an object into a String?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.

How do I convert a List of strings to a List of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);

Which method is used to convert an object to List?

toList()) can be used to collect Stream elements into a list. We can leverage this to convert object to a list. //Similarly, you can change the method in the map to convert to the datatype you need.


2 Answers

You have two options depending on the actual objects in dataRow.ItemArray

If there are actually string objects in the object[] you can just cast element wise.

dataRow.ItemArray.OfType<string>().ToList();

but if the objects are of another type, like int or something else you need to convert the to string (in this example with .ToString() but another custom method might be required in your case

dataRow.ItemArray.Select(o => o.ToString()).ToList();

Edit:
If you don't need List<string> or string[] explicitly you can leave the .ToList() out and get an IEnumerable<string> instead.

like image 50
Albin Sunnanbo Avatar answered Oct 06 '22 08:10

Albin Sunnanbo


 object[] a = new object[10];
 string[] b = Array.ConvertAll(a, p => (p ?? String.Empty).ToString())

(the line you want is the second)

like image 34
xanatos Avatar answered Oct 06 '22 10:10

xanatos