计算C#中dataGridView中第一列的重复值

时间:2019-05-21 21:33:32

标签: c# winforms datagridview count

我必须将全名及其相应的计数添加到datagridview中。我在下面的代码之前设置全名。 “全名”列中有多个重复的名称。

enter image description here

为防止这种情况,我实施了以下操作:

 bool found = false;
 int nameCount =0;
    if (dataGridView2 != null)
    {
        foreach (DataGridViewRow row in dataGridView2.Rows)
        {
            if (row.Cells[0].Value != null && row.Cells[0].Value.ToString() == fullName)
            {
                found = true;

                break;
            }
        }

        if (!found)
        {

            this.dataGridView2.Rows.Add(new object[] { fullName, nameCount });
        }
    }

这段代码基本上消除了单个名称在dataGridView中重复多次,而只添加了一次。

enter image description here

最终结果中需要的是类似以下内容的东西。我尝试在多个地方递增nameCount,但没有得到正确的结果。

enter image description here

1 个答案:

答案 0 :(得分:0)

只需设置nameCount = 1并增加Count(如果found == true

        bool found = false;
        int nameCount = 1;
        if (dataGridView1 != null)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells[0].Value != null && row.Cells[0].Value.ToString() == fullName)
                {
                    found = true;
                    row.Cells[1].Value = Convert.ToInt32(row.Cells[1].Value) + 1;
                }
            }
            if (!found)
            {
                dataGridView1.Rows.Add(new object[] { fullName, nameCount });
            }
        }

enter image description here

如果您要使用其他解决方案,请尝试

var list = dataGridView1.Rows.OfType<DataGridViewRow>()
                    .Select(x => x.Cells["FullName"].Value);

        var q = from x in list
                group x by x into g
                let count = g.Count()
                orderby count descending
                select new { FullName = g.Key, Count = count };

        foreach (var item in q)
        {
            dataGridView2.Rows.Add(new object[] { item.FullName, item.Count });
        }

有关更多信息,请查看答案herehere