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

后端 未结 2 1651
天涯浪人
天涯浪人 2021-02-10 02:39

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<         


        
相关标签:
2条回答
  • 2021-02-10 03:02

    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();
    
    0 讨论(0)
  • 2021-02-10 03:07

    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() });
    
    0 讨论(0)
提交回复
热议问题