Feed a LINQ result into a DataROW

后端 未结 3 1700
一向
一向 2021-01-03 11:37

This works:

var Result = from e in actual.Elements
                         select new
                         {
                             Key = e.Key,
          


        
相关标签:
3条回答
  • 2021-01-03 12:07

    You can write a simple extension method that takes any IEnumerable<T>, uses reflection to get the PropertyDescriptors associated with T, and creates a DataColumn for each

    public static DataTable PropertiesToDataTable(this IEnumerable<T> source)
    {
          DataTable dt = new DataTable();
    
          var props = TypeDescriptor.GetProperties(typeof(T));
    
          foreach (PropertyDescriptor prop in props)
          {
              DataColumn dc = dt.Columns.Add(prop.Name,prop.PropertyType);
              dc.Caption = prop.DisplayName;
              dc.ReadOnly = prop.IsReadOnly;
          }
    
          foreach (T item in source)
          {
                DataRow dr = dt.Rows.NewRow();
                foreach (PropertyDescriptor prop in props)
                    dr[prop.Name] = prop.GetValue(item);
    
                dt.Rows.Add(dr);
          }
    
          return dt;     
    }
    
    0 讨论(0)
  • 2021-01-03 12:17

    You might want to look into the DataTableExtensions.AsEnumerable Method

    I haven't tested this, but this might get you pointed in the right direction:

    IEnumerable<DataRow> result = (from e in actual.Elements
                                  select new DataRow
                                  {
                                      Key = e.Key,
                                      ValueNumber = e.Value.ValueNumber,
                                      ValueString = e.Value.ValueString,
                                      ValueBinary = e.Value.ValueBinary,
                                      ValueDateTime = e.Value.ValueDateTime
                                  }).AsEnumerable();
    
    DataTable dt = Result.CopyToDataTable(Result);
    
    0 讨论(0)
  • 2021-01-03 12:22

    I can't offer much help other than to point you here:

    http://blogs.msdn.com/b/aconrad/archive/2007/09/07/science-project.aspx

    0 讨论(0)
提交回复
热议问题