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
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.
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.
object a = new object; string b = Array.ConvertAll(a, p => (p ?? String.Empty).ToString())
(the line you want is the second)
List<string> strList = objArray.Cast<String>();
You may want to check for nulls first:
List<string> strList = objArray.Select( o => o == null ? String.Empty : o.ToString() ).ToList();
You can use System.Array.ConvertTo with System.Convert.ToString as the delegate.
ToArray and ToList won't quite do what you want, as they will only return an object array or list. You need to massage the data into strings first, and Select can help. Try this:
dataRow.ItemArray.Select(i => i == null ? string.Empty : i.ToString()).ToArray();