在 .NET 中使用 linq 计算 dataGridView 中列的不同值
本文关键字:dataGridView 计算 NET linq | 更新日期: 2023-09-27 18:36:22
>我需要在dataGridView中计算和呈现不同/唯一值。我想像这样呈现它,这段代码可以很好地处理列表。
List<string> aryIDs = new List<string>();
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<DataGridViewRow>()
.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() });
我认为这会做到,但我不是 100% 确定。 试试吧,如果您有任何问题,请告诉我...
var distinctRows = (from GridViewRow row in dataGridView1.Rows
select row.Cells[0]
).Distinct().Count();