Feed a LINQ result into a DataROW

后端 未结 3 1695
一向
一向 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, uses reflection to get the PropertyDescriptors associated with T, and creates a DataColumn for each

    public static DataTable PropertiesToDataTable(this IEnumerable 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;     
    }
    

提交回复
热议问题