使用.NET中的linq计算dataGridView中列的不同值

我需要在dataGridView中计算并显示不同/唯一的值。 我想像这样呈现它,这个代码适用于列表。

List aryIDs = new List(); aryIDs.Add("1234"); aryIDs.Add("4321"); aryIDs.Add("3214"); aryIDs.Add("1234"); aryIDs.Add("4321"); aryIDs.Add("1234"); var result= aryIDs.GroupBy(id => id).OrderByDescending(id => id.Count()).Select(g => new { Id = g.Key, Count = g.Count() }); 

但是,当我尝试在dataGridView中的列上使用相同的方法时,我得到一个错误,指出groupBy不能在我的dataGridView上使用。

  DataGridView dataGridView1= new DataGridView(); dataGridView1.Columns.Add("nr", "nr"); string[] row1 = new string[] { "1234" }; string[] row2 = new string[] { "4321" }; string[] row3 = new string[] { "3214" }; string[] row4 = new string[] { "1234" }; string[] row5 = new string[] { "4321" }; string[] row6 = new string[] { "1234" }; object[] rows = new object[] { row1, row2, row3, row4, row5, row6 }; foreach (string[] rowArray in rows) { dataGridView1.Rows.Add(rowArray); } var result = dataGridView1.GroupBy(id => id).OrderByDescending(id => id.Count()).Select(g => new { Id = g.Key, Count = g.Count() }); 

所以我的问题是,我如何调整这个linq语法来处理dataGridView中的列? 如果可能的话,我根本不想使用列表。

这适用于您的示例:

 var result = dataGridView1.Rows.Cast() .Where(r => r.Cells[0].Value != null) .Select (r => r.Cells[0].Value) .GroupBy(id => id) .OrderByDescending(id => id.Count()) .Select(g => new { Id = g.Key, Count = g.Count() }); 

我想这会做到,但我不是百分百肯定。 尝试一下,如果您有任何问题请告诉我…

 var distinctRows = (from GridViewRow row in dataGridView1.Rows select row.Cells[0] ).Distinct().Count();