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

时间:2025-03-12 07:54:24
var query = from g in dt_stu.AsEnumerable()
				   group g by new { 
					   t1 = <string>("STU_ID"), 
					   t2 = <string>("CLASS_ID")
				   } into m
			select new
			{
				STU_ID = .t1,
				CLASS_ID=.t2,
				成绩总合计 = (a => <decimal>("成绩")),
				优秀人数 = (a => <decimal>("成绩")>95)
			};
DataTable dt_article = (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)()).GetProperties();
			foreach (PropertyInfo pi in oProps)
			{
				Type colType = ;

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

				(new DataColumn(, colType));
			}
		}

		DataRow dr = ();

		foreach (PropertyInfo pi in oProps)
		{
			dr[] = (rec, null) == null ?  : 
			(rec, null);
		}

		(dr);
	}
	return dtReturn;
}