将Linq结果分配给Datatable

问题描述

| 我从linq查询中得到的结果是
var(IEnumrable<\'T\'> anonymous type<\'string,int>\')
我希望结果在数据表或数据集中。     

解决方法

        我为该问题找到了两个样本; 样本一: 我创建了一个称为LINQToDataTable的公共方法,如下所示:
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
     DataTable dtReturn = new DataTable();

     // column names 
     PropertyInfo[] oProps = null;

     if (varlist == null) return dtReturn;

     foreach (T rec in varlist)
     {
          // Use reflection to get property names,to create table,Only first time,others 
          will follow 
          if (oProps == null)
          {
               oProps = ((Type)rec.GetType()).GetProperties();
               foreach (PropertyInfo pi in oProps)
               {
                    Type colType = pi.PropertyType;

                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()      
                    ==typeof(Nullable<>)))
                     {
                         colType = colType.GetGenericArguments()[0];
                     }

                    dtReturn.Columns.Add(new DataColumn(pi.Name,colType));
               }
          }

          DataRow dr = dtReturn.NewRow();

          foreach (PropertyInfo pi in oProps)
          {
               dr[pi.Name] = pi.GetValue(rec,null) == null ?DBNull.Value :pi.GetValue
               (rec,null);
          }

          dtReturn.Rows.Add(dr);
     }
     return dtReturn;
}
样品二 这是我的第二种方法:
public DataTable ToDataTable(System.Data.Linq.DataContext ctx,object query)
{
     if (query == null)
     {
          throw new ArgumentNullException(\"query\");
     }

     IDbCommand cmd = ctx.GetCommand(query as IQueryable);
     SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.SelectCommand = (SqlCommand)cmd;
     DataTable dt = new DataTable(\"sd\");

     try
     {
          cmd.Connection.Open();
          adapter.FillSchema(dt,SchemaType.Source); 
          adapter.Fill(dt);
     }
     finally
     {
          cmd.Connection.Close();
     }
     return dt;
}