在C#中获取数据表中所有重复行的计数 [英] Getting count of all repeated rows in a datatable in C#

查看:688
本文介绍了在C#中获取数据表中所有重复行的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过运行存储过程来填充数据集,并且正在从数据集中填充数据表。

I am filling a dataset by running a stored procedure, and i am filling a datatable from the dataset.

DataSet RawDataSet = DataAccessHelper.RunProcedure("storedprocedureName");
//this will just return the dataset by running the procedure
DataTable RankTable = RawDataSet.Tables[0];

数据表具有以下值:

Vicky   Login   6/24/2014
Vicky   Login   6/25/2014
Arun    Game    6/26/2014
Arun    Login   6/27/2014
Kumar   Login   6/28/2014
Kumar   Game    6/29/2014
Arun    Login   6/30/2014
Arun    Login   7/1/2014
Kumar   Game    7/2/2014
Vicky   Login   7/3/2014
Arun    Login   7/4/2014
Arun    Game    7/5/2014

我想解析此dataTable并获取每个人执行一次操作的次数,即每行重复多少次:

I want to parse this dataTable and get how many times everyone has done an action, i.e how many times each row is repeated:

Vicky   Login  3
Arun    Game   2
Arun    Login  4
Kumar   Login  1
Kumar   Game   2

我是C#的新手。这可以在SQL中使用count(*)来完成,但是我需要使用C#来完成。
请让我知道是否有任何方法可以实现这一目标。

I am new to C#. This can be done using count(*) in SQL but I need to do this using C#. Please let me know if there are any ways to achieve this.

我已经搜索过SO,但所有帖子均与删除重复项/查找重复项有关,

I have searched SO but all posts are related to removing the duplicates/finding the duplicates, which does not solve my purpose.

推荐答案

您可以使用LINQ来实现,例如:

You can achieve that using LINQ like:

var query = RankTable.AsEnumerable()
                    .GroupBy(r => new { Name = r.Field<string>("Name"), Action = r.Field<string>("Action") })
                    .Select(grp => new
                    {
                        Name = grp.Key.Name,
                        Action = grp.Key.Action,
                        Count = grp.Count()
                    });

此处 Name 假定为列第一列的名称,而 Action 被假定为第二列的名称,其值包括登录名,游戏等。

Here Name is assumed to be the column name for first column, and Action is assumed to be name of second column which has values like login, game etc.

您可能会看到 LINQ to DataSet-MSDN

用于输出使用:

foreach (var item in query)
{
    Console.WriteLine("Name: {0}, Action: {1}, Count: {2}",item.Name, item.Action,item.Count);
}

这篇关于在C#中获取数据表中所有重复行的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆