将LINQ结果输入DataROW

时间:2011-07-22 01:32:26

标签: c# linq linq-to-objects

这有效:

var Result = from e in actual.Elements
                         select new
                         {
                             Key = e.Key,
                             ValueNumber = e.Value.ValueNumber,
                             ValueString = e.Value.ValueString,
                             ValueBinary = e.Value.ValueBinary,
                             ValueDateTime = e.Value.ValueDateTime
                         };

但这不起作用:

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
                };

DataTable dt = Result.CopyToDataTable(Result);

你可以帮我解决一下吗?我希望第二部分代码能够工作,这样我就可以把它放到DataTable中了。我意识到#2中的语法是完全错误的。如何使用这样的LINQ指定列?

3 个答案:

答案 0 :(得分:3)

您可以编写一个简单的扩展方法,该方法可以使用IEnumerable<T>,使用反射来获取与T关联的PropertyDescriptor,并为每个

创建DataColumn
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;     
}

答案 1 :(得分:1)

除了指点你之外,我无法提供太多帮助:

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

答案 2 :(得分:-1)

您可能需要查看DataTableExtensions.AsEnumerable Method

我没有对此进行测试,但这可能会让您指向正确的方向:

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);