如何在数据表中返回不同重复值和重复值的计数?

时间:2016-06-06 17:36:50

标签: c# asp.net datatable

我上传了一张excel表。它包含用户名列和它们注册的服务器。我想计算每个服务器上每个唯一用户名的行数。

Table:
Username | Server
bob        Production0
bob        Production1
mike       Production1
Jerry      Production2
Tom        Production0

Output:
On Production0 = 2 Unique Users (Bob and Tom)
Production1 = 2 Unique Users (Bob and Mike)
Production2 = 1 Unique Users (Jerry)

因此,对于Production0,我想弄清楚如何使用户名获得唯一的名称,但如果它在不同的服务器上也保留名称:

DataView newView = new DataView(uploadedfileDataTable);
//Get only the username and Server columns     
DataTable wantedTable = newView.ToTable(false,"Column A","Column B"); //Get only the username and Server columns
     int prodCount = wantedTable.AsEnumerable().Count(row => row.Field<string>("Column A") ==  "//HOW TO MAKE DISTINCT" && row.Field<string>("Column B") == "Production0");
     numUsersProd0.Text = prodCount.ToString();

1 个答案:

答案 0 :(得分:0)

只需按服务器名称分组,然后计算Distinct用户。

var results = watedTable.AsEnumerable()
    .GroupBy(row => row.Field<string>("Column B"))
    .Select(grp => new 
    { 
        Server = grp.Key, 
        UserCount = grp.Select(row => row.Field<string>("ColumnA")).Distinct().Count()
    });

foreach(var r in results)
    Console.WriteLine(r.Server + " has " + r.UserCount + " users.");

或者,如果您知道要为该名称过滤的服务器,请选择用户名,并计算不同的值。

var prod0Count = watedTable.AsEnumerable()
    .Where(row => row.Field<string>("Column B") == "Production0")
    .Select(row => row.Field<string>("ColumnA"))
    .Distinct()
    .Count();