我的查询是:
var query1 = from u in dc.Usage_Computers.AsEnumerable where u.DomainUser == s3 orderby u.OperationTime descending select new { u.ProgramVersion, u.OperationTime, u.IPaddress, u.ComputerName, u.DomainUser, u.OnNetwork, Operation = u.Operation == 1 ? "Login" : u.Operation == 2 ? "Logoff" : u.Operation == 3 ? "AGNS Connect" : u.Operation == 4 ? "AGNS Disconnect" : "None" }; GridView1.DataSource = query1; GridView1.DataBind();
在使用gridview进行数据绑定后,我想将结果集"query1"添加到数据集或数据表中.任何人都可以告诉我如何做到这一点?
我在这里看到另一篇文章有同样的问题,但答案在我的作品中没有用...
**注意:我使用VS 2008**
using System; using System.Collections.Generic; using System.Linq; using System.Data; public static class IEnumerableExt { public static DataTable ToDataTable(this IEnumerable things) where T : class { DataTable tbl = new System.Data.DataTable(); bool buildColumns = false; foreach (var item in things) { Type t = item.GetType(); var properties = t.GetProperties(); if (!buildColumns) { foreach (var prop in properties) { Type ptype = prop.PropertyType; if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { ptype = Nullable.GetUnderlyingType(prop.PropertyType.UnderlyingSystemType); } DataColumn col = new DataColumn(prop.Name, ptype); tbl.Columns.Add(col); } buildColumns = true; } DataRow row = tbl.NewRow(); foreach (var prop in properties) { if (prop.GetValue(item, null) == null) { row[prop.Name] = DBNull.Value; } else { row[prop.Name] = prop.GetValue(item, null); } } tbl.Rows.Add(row); } return tbl; } }
没有CopyToDataTable,除非你处理DataRows看看这些:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2162392&SiteID=1
http://oakleafblog.blogspot.com/2007/03/linq-missing-todatatable-method-saga.html
很好的选择比我的代码更多涉及:http: //blogs.msdn.com/aconrad/archive/2007/09/07/science-project.aspx
编辑:已更新,因此可以使用