简体   繁体   English

C# 计数出现次数 dataGridView

[英]C# Counting number occurences dataGridView

I'm trying to count the occurrences of some given numbers as the picture shows.如图所示,我正在尝试计算某些给定数字的出现次数。

在此处输入图像描述

Giving 5 numbers to the program i want it to output给程序 5 个数字我想要它 output

Número - Frequência R - Frequência A (1 - 2 - 0.4) (2 - 1 - 0.2) (3 - 2 - 0.4) Número - 频率 R - 频率 A (1 - 2 - 0.4) (2 - 1 - 0.2) (3 - 2 - 0.4)

Frequência R is the number of times that the number appears. Frequência R 是数字出现的次数。

My problem is counting the occurrences of the numbers and setting up the cells with the correct value.我的问题是计算数字的出现并使用正确的值设置单元格。

Frequência A is the same since I need the amount of times it appears to divide by the total number of rows. Frequência A 是相同的,因为我需要它出现的次数除以总行数。

How would I do this?我该怎么做?

Assuming dataGridView1 is bound to a DataTable ( dt in my example), or can be, you can do some Linq kung fu to project another collection that can be bound to the second grid:假设 dataGridView1 绑定到 DataTable (在我的示例中为dt ),或者可以,您可以做一些 Linq 功夫来投射另一个可以绑定到第二个网格的集合:

var projection = dt.AsEnumerable()
    .Select(n => n.Field<decimal>("Nome"))
    .GroupBy(d => d)
    .Select(d => new { Numero = d.Key, FrequenciaR = d.Count(), FrequenciaA = (decimal)d.Count() / dt.Rows.Count })
    .ToList();

This code gets the list of Nomes and groups them by their value.此代码获取 Nomes 列表并按其值对它们进行分组。 At this point you will have 3 IGroupings.此时您将拥有 3 个 IGrouping。 Then Select projects the key of the group (the number), the count of how many are in the group and finally the number divided by the number of rows in the table.然后Select组的键(数字),组中有多少的计数,最后是数字除以表中的行数。

projection is a list you can bind to the second data grid. projection是一个可以绑定到第二个数据网格的列表。 You could of course project into a class type you define.您当然可以投影到您定义的 class 类型。

UPDATE更新

You can work directly with the gridview rows though it is a bit more awkward.您可以直接使用 gridview 行,尽管它有点尴尬。 I encourage you to consider reading up on data binding collections, but try this which does the same as my first example, it just does it against the DataGridViewRowCollection instead:我鼓励您考虑阅读数据绑定 collections,但试试这个,它与我的第一个示例相同,它只是针对 DataGridViewRowCollection 执行此操作:

var projection2 = dataGridView1.Rows.Cast<DataGridViewRow>()
    .Where(dgvr => dgvr.Cells[0].Value != null) // don't count blank rows
    .Select(dgvr => (decimal)dgvr.Cells[0].Value )
    .GroupBy(d => d)
    .Select(d => new { Numero = d.Key, FrequenciaR = d.Count(), FrequenciaA = (decimal)d.Count() / (dataGridView1.Rows.Count - 1) }) // count - 1 to exclude last edit row
    .ToList();

If you have LINQPad you can run my example如果你有 LINQPad,你可以运行我的例子

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

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