转换一个对象[]数组在C#中的String []数组? [英] Converting a Object[] array to an string[] array in c#?
问题描述
我有很多方法可以做到,但还是想知道是否有任何官方的API对象[]字符串[]随着空检查转换?谢谢
I have many ways to do it but still want to know is there any offical API to convert object[] to string[] With null checked? Thanks
推荐答案
如果你要转换的对象的方法
到字符串
(或 INT
)与空检查,那么你可以使用的 Array.ConvertAll< TInput,TOutput>方法转换的 [对象]
到的String []
(或 INT []
)
If you have a method to convert an object
to a string
(or int
) with null check, then you can use the Array.ConvertAll<TInput, TOutput> Method to convert an object[]
to a string[]
(or int[]
):
object[] input = ...;
string[] result = Array.ConvertAll<object, string>(input, ConvertObjectToString);
string ConvertObjectToString(object obj)
{
return (obj == null) ? string.Empty : obj.ToString(); // FIXME
}
如果你想跳过 [对象]
数组中的项目转换为字符串时,[]
,一更方便的方法可能是使用枚举类的扩展方法:
If you want to skip items in the object[]
array when converting to a string[]
, a more convenient approach might be using the extension methods of the Enumerable Class:
object[] input = ...;
string[] result = input.Where(x => x != null)
.Select(x => x.ToString())
.ToArray();
这篇关于转换一个对象[]数组在C#中的String []数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!