计算数据表中不同的非空行

Count distinct non-null rows in a datatable

我想计算数据table列中的不同值。我发现了这个有用的技巧:

count = dataTable.DefaultView.ToTable(true, "employeeid").rows.count

如果列中没有空值,则此方法工作正常,但如果有,则计数高一。 有没有办法从计数中消除空值行,或者我是否必须遍历结果 table 寻找可能的空值?

tbl = dataTable.DefaultView.ToTable(true,"employeeid")
For Each row in tbl.rows
...
DataTable table = new DataTable();
table.Columns.Add("employeeid", typeof(int));
table.Columns.Add("employeeid2", typeof(string));
table.Rows.Add(null, null);
table.Rows.Add(100, "50");
table.Rows.Add(103, "50");
table.Rows.Add(101, "50");
table.Rows.Add(102, "52");


// This is if the column employeeid is a nullable value type
var distinctCount = table.Rows.OfType<DataRow>().DistinctBy(x => x["employeeid"]).Count(x => x["employeeid"] != null);


// This is if the column employeeid is a string type
var distinctCount2 = table.Rows.OfType<DataRow>().DistinctBy(x => x["employeeid2"]).Count(x => !string.IsNullOrWhiteSpace(x["employeeid2"].ToString()));

这是在使用 MoreLinq 库。您可以在包管理器控制台中通过 运行 this 获取此包。

Install-Package morelinq -Version 1.4.0

您可能需要临时存放。我不确定类型,但这里有一个例子..

var dataview = new DataView(dataTable);
dataview.RowFilter = "yourColumn != null";
var count = dataview.ToTable().Rows.Count;

您可以将 DataTable 中的 DataRow 集合转换为 IEnumerable,然后使用标准 Linq 进行筛选、分组和统计组数。

myDataTable.Rows.Cast<DataRow>()
            .Where(r => r.Field<int?>("EmployeeID").HasValue)
            .GroupBy(r => r.Field<int?>("EmployeeID"))
            .Count();