【问题标题】:How to get all DataColumns of a DataTable to Lists如何将 DataTable 的所有 DataColumns 获取到列表
【发布时间】:2020-10-08 21:35:10
【问题描述】:

我想在 Lists 中获取我的 DataTable 的所有 DataColumns(双类型),然后创建一个 Dictionary,其中 Key 是 DataColumn 的标题,Value 是包含 DataColumn 数据的 List。如何使用 LINQ 实现这一目标?

我尝试了以下几行但没有成功:

// Create Dictionary
Dictionary<string, List<double>> DataDic = new Dictionary<string, List<double>>(); 

// Create List
List<double> DataList = new List<double>();

// For each DataColumn save it as a List of double
DataList = (from DataColumn dc in dt.Columns select new double()).ToList();

// Add KVP to DataDic
DataDic.Add(column.ColumnName, DataList);

提前致谢。

【问题讨论】:

    标签: c# list linq datatable datacolumn


    【解决方案1】:

    这很简单:

    // Create Dictionary
    var DataDic = dt.Columns.Cast<DataColumn>()
                            .Where(dc => dc.DataType == typeof(double))
                            .ToDictionary(dc => dc.ColumnName,
                                          dc => dt.AsEnumerable()
                                                  .Select(r => r.Field<double>(dc.ColumnName))
                                                  .ToList()
                            );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多