Converting double?[ ] to object[ ] in c#

♀尐吖头ヾ 提交于 2019-12-11 12:08:42

问题


I am using DotNet.Highcharts in my C# program. The data element for series items requires an object[]. The data I’m using is coming from a LINQ method as shown below. The code below also converts the double?[] to a List<object> then to the desired object[].

double?[] data = (from c in context.CTSeries
                 select c.CTDI).Take(1000).ToArray();

List<object> dataList = new List<object>();

foreach (double? ctdi in data)
{
    dataList.Add( Convert.ChangeType(ctdi, typeof(Object)));
}

object[] dataArray = dataList.ToArray();
return dataArray;

Is there a better/more efficient way of getting the object[] from a double?[]?


回答1:


Use LINQ and cast double? to object

List<object> dataList = data.Select(d => (object)d).ToList();

or to return an array

return data.Select(d=> (object)d).ToArray();



回答2:


You can just Cast<object>() instead of creating extra intermediate array:

 double?[] data = (from c in context.CTSeries
                     select c.CTDI).Take(1000)
     .Where(v => v.HasValue) // if needed
     .Cast<object>()
     .ToArray();



回答3:


List<object> dataList = data.Select(d =>  d == null ? null : (object)d).ToList();


来源:https://stackoverflow.com/questions/29922940/converting-double-to-object-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!