计算DataGridView中具有相等值的单元格数量。

huangapple go评论66阅读模式
英文:

count DataGridView cells with equal values

问题

我有一个DataGridView,它接收一列彩票号码,我想要计算相同号码在表格列表中出现的次数,这是一个示例代码。

private void calculaTotalGrid()
{
    ResultadoNumeros numer = new ResultadoNumeros();
    int badCount = dgLista.Rows.Cast<DataGridViewRow>().Where(row => row.Cells[2].Value.ToString() == "01").Count();
    lbl_01.Text = badCount.ToString();
} 

int val;
int valToCount = 10;
int count = 0;
foreach (var row in dgLista.Rows.Cast<DataGridViewRow>())
    foreach (var cell in row.Cells.Cast<DataGridViewCell>())
        count += int.TryParse(cell.Value?.ToString(),
            out val) && val == valToCount ? 1 : 0;
txtNum.Text = count.ToString();

请问有人可以帮助我或者给我一点提示如何做到这一点吗?

我的类 ResultadoNumeros

public int concurso { get; set; }
public int _01 { get; set; }
// 其他属性 _02 到 _15

类的方法 ObterNumeros 用于获取数据:

public static DataTable ObterNumeros()
{
    DataTable tabela = new DataTable();
    DALConexao conexao = new DALConexao(DadosDaConexao.StringDaConexao);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conexao.ObjetConexao;
    SqlDataAdapter da = new SqlDataAdapter("Select * from TBLotofacil ORDER BY Concurso DESC", conexao.StringConexao);
    da.Fill(tabela);
    return tabela;
}        

请注意,这只是代码的一部分,没有包括完整的上下文。如果您需要更多帮助,请提供更多信息。

英文:

I have a DataGridView that receives a list of lottery numbers, I would like to count how many times the same number appeared in the grid list, I have an image for example, I am using this code.
enter image description here

private void calculaTotalGrid()
    {
        ResultadoNumeros numer = new ResultadoNumeros();
        int badCount = dgLista.Rows.Cast&lt;DataGridViewRow&gt;().Where(row =&gt; row.Cells[2].Value.ToString() == &quot;01&quot;).Count();
        lbl_01.Text = badCount.ToString();
    } 

          int val;
        int valToCount = 10;
        int count = 0;
        foreach (var row in dgLista.Rows.Cast&lt;DataGridViewRow&gt;())
            foreach (var cell in row.Cells.Cast&lt;DataGridViewCell&gt;())
                count += int.TryParse(cell.Value?.ToString(),
                    out  val) &amp;&amp; val == valToCount ? 1 : 0;
                       txtNum.Text = count.ToString();

Could someone help me or give me a light on how to do this?
minha class ResultadoNumeros

public int concurso { get; set; }
    public int _01 { get; set; }
    ----
    public int _15 { get; set; }

class

public static DataTable ObterNumeros()
    {
        DataTable tabela = new DataTable();
        DALConexao conexao = new DALConexao(DadosDaConexao.StringDaConexao);
         SqlCommand cmd = new SqlCommand();
          cmd.Connection = conexao.ObjetConexao;
            SqlDataAdapter da = new SqlDataAdapter(&quot;Select * from TBLotofacil ORDER BY Concurso DESC&quot;, conexao.StringConexao);
             da.Fill(tabela);
        return tabela;
    }        
}

答案1

得分: 1

以下是您要翻译的内容:

"Many ways to solve this problem. The simplest is to traverse the grid's .Rows and their .Cells to count the occurrence of the given value.

private void calculaTotalGrid()
{
    int valToCount = 10;
    int count = 0;

    foreach (var row in dgLista.Rows.Cast&lt;DataGridViewRow&gt;())
        foreach (var cell in row.Cells.Cast&lt;DataGridViewCell&gt;())
            count += int.TryParse(cell.Value?.ToString(), out int val) &amp;&amp;
                val == valToCount ? 1 : 0;

    txtNum.Text = count.ToString();
}
```"

"Or, execute a `Linq` query to [flatten][1] the grid's cells into a sequence and count the cells of the given value.

```c#
var count = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
    .SelectMany(r =&gt; r.Cells.Cast&lt;DataGridViewCell&gt;()
    .Where(c =&gt; int.TryParse(c.Value?.ToString(), out int val) &amp;&amp; val == valToCount))
    .Count();
```"

"Or, use the [`Enumerable.Aggregate`][2] method instead.

```c#
var count = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
    .Aggregate(0, (total, row) =&gt; total += row.Cells
    .Cast&lt;DataGridViewCell&gt;()
    .Count(c =&gt; c.Value != null &amp;&amp; int.Parse(c.Value.ToString()) == valToCount));
```"

"According to your last revision and comments, you need to get the count of the distinct values starting from column 1 (`concurso` column is not included). If so, I suggest a one-liner `Linq` query to group the cells by their unique values and create a `Dictionary&lt;int, int&gt;` instead of the `ResultadoNumeros` class. This way, you don't need to repeat one of the previous solutions for each value.

```c#
private Dictionary&lt;int, int&gt; ResultadoNumeros;

private void calculaTotalGrid()
{
    int outVal = 0;
    ResultadoNumeros = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
        .SelectMany(r =&gt; r.Cells.Cast&lt;DataGridViewCell&gt;()
        .Where(c =&gt; c.ColumnIndex &gt; 0 &amp;&amp; int.TryParse(c.Value?.ToString(), out outVal)))
        .GroupBy(c =&gt; int.Parse(c.Value.ToString()))
        .ToDictionary(x =&gt; x.Key, x =&gt; x.Count());

    foreach (var kvp in ResultadoNumeros)
        Console.WriteLine($&quot;{kvp.Key} -&gt; {kvp.Value}&quot;);
}
```"

"To get the count of value `15` for example:

```c#
int count15 = ResultadoNumeros[15];
```"

"Or call the `TryGetValue` method to avoid throwing the `KeyNotFoundException` if the dictionary does not contain a given `Key`.

```c#
int outVal = 0;

if (ResultadoNumeros.TryGetValue(15, out outVal))
    Console.WriteLine(outVal);
```"

"See also:

+ [Dictionary&lt;TKey,TValue&gt;.Keys][3] property.
+ [Dictionary&lt;TKey,TValue&gt;.ContainsKey(TKey)][4] method.
+ [Dictionary&lt;TKey,TValue&gt;.Values][5] property.
+ [Dictionary&lt;TKey,TValue&gt;.ContainsValue(TValue)][6] method.
 
  [1]: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Linq.Enumerable.SelectMany%2560%25602)%3Bk(TargetFrameworkMoniker-.NETFramework%2CVersion%253Dv4.8)%3Bk(DevLang-csharp)%26rd%3Dtrue&amp;view=net-7.0
  [2]: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Linq.Enumerable.Aggregate%2560%25601)%3Bk(TargetFrameworkMoniker-.NETFramework%2CVersion%253Dv4.8)%3Bk(DevLang-csharp)%26rd%3Dtrue&amp;view=net-7.0#system-linq-enumerable-aggregate-2(system-collections-generic-ienumerable((-0))-1-system-func((-1-0-1)))
  [3]: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Collections.Generic.Dictionary%25602.Keys)%3Bk(TargetFrameworkMoniker-.NETFramework%2CVersion%253Dv4.8)%3Bk(DevLang-csharp)%26rd%3Dtrue&amp;view=net-7.0#definition
  [4]: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.containskey?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Collections.Generic.Dictionary%25602.ContainsKey)%3Bk(TargetFrameworkMoniker-.NETFramework%2CVersion%253Dv4.8)%3Bk(DevLang-csharp)%26rd%3Dtrue&amp;view=net-7.0
  [5]: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.values?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Collections.Generic.Dictionary%25602.Values)%3Bk(TargetFrameworkMoniker-.NETFramework%2CVersion%253Dv4.8)%3Bk(DevLang-csharp)%26rd%3Dtrue&amp;view=net-7.0
  [6]: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.containsvalue?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Collections.Generic.Dictionary%25602.ContainsValue)%3Bk(TargetFrameworkMoniker-.NETFramework%2CVersion%253Dv4.8)%3Bk(DevLang-csharp)%26rd%3Dtrue&amp;view=net-7.0"

<details>
<summary>英文:</summary>

Many ways to solve this problem. The simplest is to traverse the grid&#39;s `.Rows` and their `.Cells` to count the occurrence of the given value.

```c#
private void calculaTotalGrid()
{
    int valToCount = 10;
    int count = 0;

    foreach (var row in dgLista.Rows.Cast&lt;DataGridViewRow&gt;())
        foreach (var cell in row.Cells.Cast&lt;DataGridViewCell&gt;())
            count += int.TryParse(cell.Value?.ToString(), out int val) &amp;&amp;
                val == valToCount ? 1 : 0;

    txtNum.Text = count.ToString();
}

Or, execute a Linq query to flatten the grid's cells into a sequence and count the cells of the given value.

var count = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
    .SelectMany(r =&gt; r.Cells.Cast&lt;DataGridViewCell&gt;()
    .Where(c =&gt; int.TryParse(c.Value?.ToString(), out int val) &amp;&amp; val == valToCount))
    .Count();

Or, use the Enumerable.Aggregate method instead.

var count = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
    .Aggregate(0, (total, row) =&gt; total += row.Cells
    .Cast&lt;DataGridViewCell&gt;()
    .Count(c =&gt; c.Value != null &amp;&amp; int.Parse(c.Value.ToString()) == valToCount));

According to your last revision and comments, you need to get the count of the distinct values starting from column 1 (concurso column is not included). If so, I suggest a one-liner Linq query to group the cells by their unique values and create a Dictopnary&lt;int, int&gt; instead of the ResultadoNumeros class. This way, you don't need to repeat one of the previous solutions for each value.

private Dictionary&lt;int, int&gt; ResultadoNumeros;

private void calculaTotalGrid()
{
    int outVal = 0;
    ResultadoNumeros = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
        .SelectMany(r =&gt; r.Cells.Cast&lt;DataGridViewCell&gt;()
        .Where(c =&gt; c.ColumnIndex &gt; 0 &amp;&amp; int.TryParse(c.Value?.ToString(), out outVal)))
        .GroupBy(c =&gt; int.Parse(c.Value.ToString()))
        .ToDictionary(x =&gt; x.Key, x =&gt; x.Count());

    foreach (var kvp in ResultadoNumeros)
        Console.WriteLine($&quot;{kvp.Key} -&gt; {kvp.Value}&quot;);
}

To get the count of value 15 for example:

int count15 = ResultadoNumeros[15];

Or call the TryGetValue method to avoid throwing the KeyNotFoundException if the dictionary does not contain a given Key.

int outVal = 0;

if (ResultadoNumeros.TryGetValue(15, out outVal))
    Console.WriteLine(outVal);

See also:

huangapple
  • 本文由 发表于 2023年6月15日 08:45:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定