简体   繁体   中英

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.

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.

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

(the line you want is the second)

List<string> strList = objArray.Cast<String>();

您可能想先检查空值:

List<string> strList = objArray.Select( o => o == null ? String.Empty : o.ToString() ).ToList();

您可以使用System.Array.ConvertToSystem.Convert.ToString作为委托。

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM