You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计DataGridView列中重复值并在对应首行显示计数

DataGridView重复值统计并填充首行Count列

实现步骤

  • 第一步:统计各Personal代码的出现次数
    用字典存储每个代码对应的出现次数,遍历所有行完成计数。
  • 第二步:填充首行Count列
    用集合记录已处理的代码,避免重复填充,遍历行时找到每个代码的第一行,把统计结果填入Count列。

C# 实现代码

// 统计Personal列的重复次数
Dictionary<string, int> countDict = new Dictionary<string, int>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    // 跳过新增的空白行
    if (row.IsNewRow) continue;
    
    string personalCode = row.Cells["Personal"].Value?.ToString();
    if (!string.IsNullOrEmpty(personalCode))
    {
        countDict[personalCode] = countDict.TryGetValue(personalCode, out int count) ? count + 1 : 1;
    }
}

// 为每个Personal代码的首行填充Count列
HashSet<string> processedCodes = new HashSet<string>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.IsNewRow) continue;
    
    string personalCode = row.Cells["Personal"].Value?.ToString();
    if (!string.IsNullOrEmpty(personalCode) && !processedCodes.Contains(personalCode))
    {
        row.Cells["Count"].Value = countDict[personalCode];
        processedCodes.Add(personalCode);
    }
}

注意事项

  • 请确保代码中"Personal"和"Count"与你的DataGridView实际列名一致,不一致时直接替换即可。
  • 如果Personal列存储的是数值类型(如int),可将代码中的string改为对应类型,省去ToString转换步骤。
  • 代码中处理了空值情况,避免因单元格值为空导致的空引用异常。

内容的提问来源于stack exchange,提问作者Mostafa Amini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:53:41