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

时间:2016-05-27 20:22:28

标签: c# vb.net datatable distinct

我想计算数据表列中的不同值。我找到了这个有用的技术:

tbl = dataTable.DefaultView.ToTable(true,"employeeid")
For Each row in tbl.rows
...

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

Impression Clicks CTR Average Top Position 
    xxx     yyy     zzzz          xyz

3 个答案:

答案 0 :(得分:3)

您可能需要进入临时存储空间。我不确定这种类型,而是一个例子......

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

答案 1 :(得分:3)

您可以将DataTable中的DataRow集合强制转换为IEnumerable,然后使用标准Linq过滤,分组和计算组数。

#include <type_traits>
#include <iostream>
#include <fit/is_callable.hpp>

// std::less doesn't SFINAE, so we make our own test
struct less_test {
    template<typename L, typename R>
    auto operator()(L l, R r) -> decltype(l < r);
};

template<typename T>
using is_less_than_comparable = fit::is_callable<less_test, T, T>;

// operator< version (replace with your implementation)
template <typename T> constexpr auto
do_stuff(T arg, const std::true_type&) {
    return std::integral_constant<int, 0>{};
}

// other version (replace with your implementation)
template <typename T> constexpr auto
do_stuff(T arg, const std::false_type&) {
    return std::integral_constant<int, 1>{};
}

template <typename T> constexpr auto
do_stuff(T arg) {
    return do_stuff(arg, is_less_than_comparable<T>{});
}

struct foo {};

int main() {

    //is not less-than comparable
    static_assert(do_stuff(foo{}) == 1, "");

    //is less-than comparable
    static_assert(do_stuff(0) == 0, "");
}

答案 2 :(得分:0)

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。您可以通过在包管理器控制台中运行此包来获取此包。

Install-Package morelinq -Version 1.4.0