gpt4 book ai didi

c# - 将我的 linq 查询结果集添加到数据集,c# asp.net 3.5

转载 作者:行者123 更新时间:2023-11-30 14:44:32 25 4
gpt4 key购买 nike

我的查询是:

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 进行数据绑定(bind)后,我想将结果集“query1”添加到数据集或数据表中。谁能告诉我该怎么做?

我在这里看到另一篇帖子也有同样的问题,但那个答案在我身上不起作用......

**注意:我使用的是 VS 2008 **

最佳答案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;

public static class IEnumerableExt
{
public static DataTable ToDataTable<T>(this IEnumerable<T> 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

编辑:更新后可以正常工作

关于c# - 将我的 linq 查询结果集添加到数据集,c# asp.net 3.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/287199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com