How to Count Duplicates in Datagridview in C#

醉酒当歌 提交于 2019-12-25 04:22:08

问题


how to do it?

I've fount this code in How to Count Duplicates in List with LINQ :

 var list = new List<string> { "a", "b", "a", "c", "a", "b" };

        var q = from x in list
                group x by x into g
                let count = g.Count()
                orderby count descending
                select new { Value = g.Key, Count = count };
        foreach (var x in q)
        {
            MessageBox.Show("Value: " + x.Value + " Count: " + x.Count);
        }

But how to modify it to count duplicates in datagridview? For example datagridview1[7,i] where i is number of rows in datagriview.

EDIT

Now my code is looking like that:

      var list = dataGridView1.Rows.OfType<DataGridViewRow>()
       .GroupBy(x => x.Cells["TestValues"].Value)
       .Select(g => new { Value = g.Key, Count = g.Count(), Rows = g.ToList() })
       .OrderByDescending(x => x.Count);

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

        foreach (var x in q)
        {
           // dataGridView1[7, x].Value.ToString();

            MessageBox.Show("Value: " + x.Value + " Count: " + x.Count +"Rows: " );

        }

回答1:


Something like this should work:

var list = myDataGridView.Rows.OfType<DataGridViewRow>()
           .Select(x => x.Cells["MYCOLUMN"].Value.ToString());
var q = from x in list
    group x by x into g
    let count = g.Count()
    orderby count descending
    select new { Value = g.Key, Count = count };

where "MYCOLUMN" is the name of the column that you want, or, alternatively, you can pass the column index.

EDIT :

this code returns a list of items that contains also the list of rows with the duplications:

var q = myDataGridView.Rows.OfType<DataGridViewRow>()
        .GroupBy(x => x.Cells["MYCOLUMN"].Value.ToString())
        .Select(g => new {Value=g.Key, Count=g.Count(), Rows=g.ToList()})
        .OrderByDescending(x => x.Count);

so if you have 5 rows e.g. :

ID     MYCOLUMN
 0         A
 1         B
 2         C
 3         A
 4         B   

q will contain 3 elements:

 Key="A", Count=2, Rows={ [0 - A] [3 - A]}
 Key="B", Count=2, Rows={ [1 - B] [4 - B]}
 Key="C", Count=1, Rows={ [2 - C] }


来源:https://stackoverflow.com/questions/9600950/how-to-count-duplicates-in-datagridview-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!