分享

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

 羊玉wngbx 2019-02-16
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;
}
--------------------- 
作者:jyh_jack 
来源:CSDN 
原文:https://blog.csdn.net/jyh_jack/article/details/80995537 
版权声明:本文为 jyh_jack 原创文章转载

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多