Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 508
Zeezer Avatar asked Jun 05 '12 14:06

Zeezer


2 Answers

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() });
like image 54
Brad Rem Avatar answered Sep 26 '22 23:09

Brad Rem


I think this will do it, but I'm not 100% sure. Try it out, if you have any issues let me know...

var distinctRows = (from GridViewRow row in dataGridView1.Rows 
                    select row.Cells[0]
                   ).Distinct().Count();
like image 31
Faraday Avatar answered Sep 23 '22 23:09

Faraday