Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DataTable 分组查询 #18

Open
huangshuwei opened this issue Sep 30, 2018 · 0 comments
Open

DataTable 分组查询 #18

huangshuwei opened this issue Sep 30, 2018 · 0 comments

Comments

@huangshuwei
Copy link
Owner

huangshuwei commented Sep 30, 2018

前言

现在都流行匿名类,很少创建实体对象。当 DataTable 数据需要进行分组查询时,还是比较繁琐的。

DataTable 数据结构

id name type
1 abc 分组1
2 dsad 分组1
3 121 分组1
4 das 分组1
5 afdfbc 分组2
6 rgrfdsad 分组3

将DataTable 数据根据 type 字段分组

IEnumerable<IGrouping<string, DataRow>> groupResult = dt.Rows.Cast<DataRow>().OrderBy<DataRow, string>(dr => dr["type"].ToString()).GroupBy<DataRow, string>(dr => dr["type"].ToString());

            var groupList = new List<object>();

            foreach (IGrouping<string, DataRow> gr in groupResult)
            {
                // 获取当前分组数据
                var groupType = gr.Key;

                var groupListItem = new List<object>();
                foreach (var dr in gr)
                {
                    var row = new
                    {
                        id = dr["id"].ToString(),
                        name = dr["name"].ToString()
                    };

                    groupListItem.Add(row);
                }
                groupList.Add(new
                {
                    groupType,
                    groupListItem
                });
            }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant