12

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

5 Answers 5

21

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 For talking about both coercion and conversion. Consider mentioning/handling null/DBNull in conversion example as these are somewhat common cases (in my experience).
10
 object[] a = new object[10];
 string[] b = Array.ConvertAll(a, p => (p ?? String.Empty).ToString())

(the line you want is the second)

Comments

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

2 Comments

Should point out that this does not cause conversion which may (or may not be) desired.
The second example is not just the first-with-a-null-check but an explicit conversion. This should be pointed out.
4

You can use System.Array.ConvertTo with System.Convert.ToString as the delegate.

Comments

3

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

1 Comment

I prefer "" + i in this case as it has the same effect as the ternary w.r.t. nulls -- but style-subjective :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.