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

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

猜你喜欢

转载自blog.csdn.net/jyh_jack/article/details/80995537