C# 通过LINQ对DataTable数据查询,结果生成DataTable

本文介绍了一种使用LINQ进行分组统计查询,并将查询结果转换为DataTable的方法。通过具体的C#代码示例展示了如何从数据源中按学生ID和班级ID进行分组,计算每个分组的成绩总和及优秀人数,最后将这些信息整合到DataTable中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

var query = from g in dt_stu.AsEnumerable()
				   group g by new { 
					   t1 = g.Field<string>("STU_ID"), 
					   t2 = g.Field<string>("CLASS_ID")
				   } into m
			select new
			{
				STU_ID = m.Key.t1,
				CLASS_ID=m.Key.t2,
				成绩总合计 = m.Sum(a => a.Field<decimal>("成绩")),
				优秀人数 = m.Count(a => a.Field<decimal>("成绩")>95)
			};
DataTable dt_article = UserClass.ToDataTable(query);



/// <summary>
/// LINQ返回DataTable类型
/// </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="varlist"> </param>
/// <returns> </returns>
public static DataTable ToDataTable<T>(IEnumerable<T> varlist)
{
	DataTable dtReturn = new DataTable();

	// column names
	PropertyInfo[] oProps = null;

	if (varlist == null)
		return dtReturn;

	foreach (T rec in varlist)
	{
		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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值