c# - 如何将字符串数组转换为 IList<SomeType>?

标签 c# linq

我正在尝试将数据表列转换为系列数组(稍后我将使用它将它们序列化为 Json),但不确定如何将字符串数组转换为 IList?或者也许我应该使用其他方法?但不知道如何将字符串数组转换为 IList<SeriesValue> ?或者也许我应该使用其他方法?

public Series[] GetGraphData(string sp)
    {
        var connection = ConfigurationManager.ConnectionStrings["EFDbContext"].ConnectionString;
        using (var da = new SqlDataAdapter("exec " + sp, connection))
        {
            var dt = new DataTable();

            da.Fill(dt);
            da.FillSchema(dt, SchemaType.Mapped);

            Series[] arrSeries = new Series[dt.Columns.Count];

            foreach(DataColumn dc in dt.Columns)
            {
                if (dc.Ordinal == 0)
                {

                }
                else
                {
                    Series s = new Series()
                    {
                        seriesname = dc.ColumnName,
                        renderas = "Line",
                        data = dt.Rows.Cast<DataRow>().Select(row => row[dc.Ordinal]).Cast<SeriesValue>().ToList()
                    };

                    arrSeries[dc.Ordinal] = s;
                }
            }

            return arrSeries;
        }
    }



 public class Series
{
    public string seriesname { get; set; }
    public string renderas { get; set; }
    public IList<SeriesValue> data { get; set; }
}

public class SeriesValue
{
    public string value { get; set; }
}

Json 格式示例:

{
                        "seriesname": "Input",
                        "renderas": "Line",
                        "data": [
                            {
                                "value": "6500"
                            },
                            {
                                "value": "6500"
                            },
                            {
                                "value": "6500"
                            }
}

非常感谢任何帮助?

最佳答案

您可以将字符串转换为对象,如下所示:

给定:strarr = 字符串数组

data = strarr.Select(o => new SeriesValue { value = o }).ToList()

现在数据是 List<SeriesValue> ,它实现 IList<SeriesValue> .

关于c# - 如何将字符串数组转换为 IList<SomeType>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30488331/

相关文章:

c# - 从 wpf 中的其他窗口更改框架源

c# - 如何从事件处理程序中更改值参数?

c# - 网络共享上的 .NET 4.0 应用程序导致 SecurityException

c# - Linq OrderBy 不对 List<T> 进行排序。我如何对列表进行排序?

c# - 使用 Rx 尝试某件事 5 次

c# - Foreach while 一个值与前一个值相同

c# - 为什么我不能将 Foo<Bar> 转换为 IFoo<IBar>

c# - MVVM动态UserControl创建

linq - 使用 LINQ 规范化数据

c# - Linq 选择 : Set specific value for first occurrence only