【问题标题】:Count distinct non-null rows in a datatable计算数据表中不同的非空行
【发布时间】:2016-05-27 20:22:28
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我怀疑一点 LINQ 会帮助你。在不知道头顶上方每个部分的类型的情况下,我无法说出将其放置在何处,但可能在行和计数之间。
  • @ManoDestra 你是对的。有一些很棒的库,例如 MoreLINQ,可以帮助解决这样的问题。
  • Basic LINQ 没有额外的库就足够了。这里不需要。

标签: c# vb.net datatable distinct


【解决方案1】:

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

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

【讨论】:

  • 谢谢大家。该解决方案完美运行,并向我介绍了 RowFilter。这是我使用 Visual Studio (VB.NET) 的第 2 个月;我还有很多东西要学。 StackOverflow 是最好的!
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-27
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2012-01-31
      相关资源
      最近更新 更多