简体   繁体   English

使用.NET中的linq计算dataGridView中列的不同值

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

I need to count and present distinct/unique values in a dataGridView. 我需要在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中的列上使用相同的方法时,我得到一个错误,指出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() });

So my question is, how do I adapt this linq syntax to work with a column in dataGridView? 所以我的问题是,我如何调整这个linq语法来处理dataGridView中的列? If possible, i dont want to use lists at all. 如果可能的话,我根本不想使用列表。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM