Count distinct values of a column in dataGridView using linq in .NET

.net, c#, datagridview, lambda, linq

Solution

This will work for your example:

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

Problem

I need to count and present distinct/unique values in a dataGridView. I want to present it like this, and this code works just fine with lists. ``` 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() }); ``` But when I try to use the same approach on a column in dataGridView I get an error saying that groupBy cannot be used on my 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() }); ``` So my question is, how do I adapt this linq syntax to work with a column in dataGridView? If possible, i dont want to use lists at all.

Original source