C#用DataTable实现Group by数据统计
发布日期:2021-11-15 03:27:10 浏览次数:4 分类:技术文章

本文共 755 字,大约阅读时间需要 2 分钟。

使用linq to DataTable group by实现

var
 query = 
from
 t 
in
 dt.AsEnumerable()

            group t by 
new
 { t1 = t.Field<
string
>(
"
name
"
), t2 = t.Field<
string
>(
"
sex
"
) } into m

            
select
 
new

            {

                name = m.Key.t1,

                sex = m.Key.t2,

                score = m.Sum(n => n.Field<
decimal
>(
"
score
"
))

            };

if
 (query.ToList().Count > 
0
)

{

    query.ToList().ForEach(q =>

    {

        Console.WriteLine(q.name + 
"
,
"
 + q.sex + 
"
,
"
 + q.score);

    });

} 

衍生使用

public class Student

{

public string name {get;set;}

public string sex {get;set;}

public decimal score {get;set;}

}

List<Student> query = from t in dt.AsEnumerable()
            group t by new { t1 = t.Field<string>("name"), t2 = t.Field<string>("sex") } into m
            select new

    Student
            {


                name = m.Key.t1,
                sex = m.Key.t2,
                score = m.Sum(n => n.Field<decimal>("score"))
            };

转载地址:https://blog.csdn.net/qq_30469045/article/details/51540873 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:最公正海贼王实力排行TOP50!
下一篇:linq any()方法实现sql in()方法的效果

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年03月31日 19时01分34秒