使用.NET中的linq计算dataGridView中列的不同值 [英] Count distinct values of a column in dataGridView using linq in .NET

查看:197
本文介绍了使用.NET中的linq计算dataGridView中列的不同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在dataGridView中计数和显示不同/唯一的值。
我想这样呈现,这个代码与列表一样正常。

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

但是,当我尝试在dataGridView中的列上使用相同的方法时,会收到一条错误,表示groupBy不能在我的dataGridView上使用。

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

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

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.

推荐答案

这将适用于您的示例:

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

这篇关于使用.NET中的linq计算dataGridView中列的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆