且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中的Datagridview中计算重复项

更新时间:2022-12-09 20:49:56

类似这应该起作用:

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 };

其中 MYCOLUMN

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);

因此,如果您有5行,例如:

so if you have 5 rows e.g. :

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

q 将包含3个元素:

 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] }