简体   繁体   English

将Object []转换为String []或List的最佳方法<String>

[英]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[] . 我可以使用属性dataRow.ItemArray获取其中的项目,类型为object[] I need to convert this to String[] or List<String> 我需要将其转换为String[]List<String>

I see the methods ToArray<> and ToList<> . 我看到方法ToArray<>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 根据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 但是如果对象是另一种类型,比如int或其他什么你需要转换为字符串(在这个例子中使用.ToString()但在你的情况下可能需要另一个自定义方法

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. 如果您不需要明确地使用List<string>string[] ,则可以保留.ToList()并获取IEnumerable<string>

 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. ToArray和ToList不会完全按照你的意愿行事,因为它们只会返回一个对象数组或列表。 You need to massage the data into strings first, and Select can help. 您需要先将数据按到字符串中,然后Select可以提供帮助。 Try this: 尝试这个:

 dataRow.ItemArray.Select(i => i == null ? string.Empty : i.ToString()).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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