从List <myclass>中选择数据,其中class属性为List <double>并在DataTable中显示结果

时间:2018-12-14 04:11:58

标签: c# list linq datatable

我有一堂课

public class MyClass
{
    public uint ID { get; set; }
    public List<double> Values { get; set; }
}

然后,我正在创建一个类对象列表:

List<MyClass> objects = new List<MyClass>(); // then I add the data to this list

现在,我需要从 对象 中选择数据,例如:

var query = objects.Select(o => new { o.ID, o.Values } ).ToList(); // this example show only ID field in DataTable

并像这样将结果转换为DataTable:

public DataTable ConvertToDataTable<T>(IList<T> data)
{
    DataTable table = new DataTable();
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));          

    foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

    foreach (T item in data)
    {
        DataRow row = table.NewRow();

        foreach (PropertyDescriptor prop in properties)
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;

        table.Rows.Add(row);
    }

    return table;
}

因此,我需要进行类似交叉表查询的操作。我该怎么办?

0 个答案:

没有答案