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

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

count DataGridView cells with equal values

问题

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

  1. private void calculaTotalGrid()
  2. {
  3. ResultadoNumeros numer = new ResultadoNumeros();
  4. int badCount = dgLista.Rows.Cast<DataGridViewRow>().Where(row => row.Cells[2].Value.ToString() == "01").Count();
  5. lbl_01.Text = badCount.ToString();
  6. }
  7. int val;
  8. int valToCount = 10;
  9. int count = 0;
  10. foreach (var row in dgLista.Rows.Cast<DataGridViewRow>())
  11. foreach (var cell in row.Cells.Cast<DataGridViewCell>())
  12. count += int.TryParse(cell.Value?.ToString(),
  13. out val) && val == valToCount ? 1 : 0;
  14. txtNum.Text = count.ToString();

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

我的类 ResultadoNumeros

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

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

  1. public static DataTable ObterNumeros()
  2. {
  3. DataTable tabela = new DataTable();
  4. DALConexao conexao = new DALConexao(DadosDaConexao.StringDaConexao);
  5. SqlCommand cmd = new SqlCommand();
  6. cmd.Connection = conexao.ObjetConexao;
  7. SqlDataAdapter da = new SqlDataAdapter("Select * from TBLotofacil ORDER BY Concurso DESC", conexao.StringConexao);
  8. da.Fill(tabela);
  9. return tabela;
  10. }

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

英文:

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

  1. private void calculaTotalGrid()
  2. {
  3. ResultadoNumeros numer = new ResultadoNumeros();
  4. int badCount = dgLista.Rows.Cast&lt;DataGridViewRow&gt;().Where(row =&gt; row.Cells[2].Value.ToString() == &quot;01&quot;).Count();
  5. lbl_01.Text = badCount.ToString();
  6. }
  7. int val;
  8. int valToCount = 10;
  9. int count = 0;
  10. foreach (var row in dgLista.Rows.Cast&lt;DataGridViewRow&gt;())
  11. foreach (var cell in row.Cells.Cast&lt;DataGridViewCell&gt;())
  12. count += int.TryParse(cell.Value?.ToString(),
  13. out val) &amp;&amp; val == valToCount ? 1 : 0;
  14. txtNum.Text = count.ToString();

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

  1. public int concurso { get; set; }
  2. public int _01 { get; set; }
  3. ----
  4. public int _15 { get; set; }

class

  1. public static DataTable ObterNumeros()
  2. {
  3. DataTable tabela = new DataTable();
  4. DALConexao conexao = new DALConexao(DadosDaConexao.StringDaConexao);
  5. SqlCommand cmd = new SqlCommand();
  6. cmd.Connection = conexao.ObjetConexao;
  7. SqlDataAdapter da = new SqlDataAdapter(&quot;Select * from TBLotofacil ORDER BY Concurso DESC&quot;, conexao.StringConexao);
  8. da.Fill(tabela);
  9. return tabela;
  10. }
  11. }

答案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.

  1. private void calculaTotalGrid()
  2. {
  3. int valToCount = 10;
  4. int count = 0;
  5. foreach (var row in dgLista.Rows.Cast&lt;DataGridViewRow&gt;())
  6. foreach (var cell in row.Cells.Cast&lt;DataGridViewCell&gt;())
  7. count += int.TryParse(cell.Value?.ToString(), out int val) &amp;&amp;
  8. val == valToCount ? 1 : 0;
  9. txtNum.Text = count.ToString();
  10. }
  11. ```"
  12. "Or, execute a `Linq` query to [flatten][1] the grid's cells into a sequence and count the cells of the given value.
  13. ```c#
  14. var count = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
  15. .SelectMany(r =&gt; r.Cells.Cast&lt;DataGridViewCell&gt;()
  16. .Where(c =&gt; int.TryParse(c.Value?.ToString(), out int val) &amp;&amp; val == valToCount))
  17. .Count();
  18. ```"
  19. "Or, use the [`Enumerable.Aggregate`][2] method instead.
  20. ```c#
  21. var count = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
  22. .Aggregate(0, (total, row) =&gt; total += row.Cells
  23. .Cast&lt;DataGridViewCell&gt;()
  24. .Count(c =&gt; c.Value != null &amp;&amp; int.Parse(c.Value.ToString()) == valToCount));
  25. ```"
  26. "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.
  27. ```c#
  28. private Dictionary&lt;int, int&gt; ResultadoNumeros;
  29. private void calculaTotalGrid()
  30. {
  31. int outVal = 0;
  32. ResultadoNumeros = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
  33. .SelectMany(r =&gt; r.Cells.Cast&lt;DataGridViewCell&gt;()
  34. .Where(c =&gt; c.ColumnIndex &gt; 0 &amp;&amp; int.TryParse(c.Value?.ToString(), out outVal)))
  35. .GroupBy(c =&gt; int.Parse(c.Value.ToString()))
  36. .ToDictionary(x =&gt; x.Key, x =&gt; x.Count());
  37. foreach (var kvp in ResultadoNumeros)
  38. Console.WriteLine($&quot;{kvp.Key} -&gt; {kvp.Value}&quot;);
  39. }
  40. ```"
  41. "To get the count of value `15` for example:
  42. ```c#
  43. int count15 = ResultadoNumeros[15];
  44. ```"
  45. "Or call the `TryGetValue` method to avoid throwing the `KeyNotFoundException` if the dictionary does not contain a given `Key`.
  46. ```c#
  47. int outVal = 0;
  48. if (ResultadoNumeros.TryGetValue(15, out outVal))
  49. Console.WriteLine(outVal);
  50. ```"
  51. "See also:
  52. + [Dictionary&lt;TKey,TValue&gt;.Keys][3] property.
  53. + [Dictionary&lt;TKey,TValue&gt;.ContainsKey(TKey)][4] method.
  54. + [Dictionary&lt;TKey,TValue&gt;.Values][5] property.
  55. + [Dictionary&lt;TKey,TValue&gt;.ContainsValue(TValue)][6] method.
  56. [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
  57. [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)))
  58. [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
  59. [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
  60. [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
  61. [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"
  62. <details>
  63. <summary>英文:</summary>
  64. 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.
  65. ```c#
  66. private void calculaTotalGrid()
  67. {
  68. int valToCount = 10;
  69. int count = 0;
  70. foreach (var row in dgLista.Rows.Cast&lt;DataGridViewRow&gt;())
  71. foreach (var cell in row.Cells.Cast&lt;DataGridViewCell&gt;())
  72. count += int.TryParse(cell.Value?.ToString(), out int val) &amp;&amp;
  73. val == valToCount ? 1 : 0;
  74. txtNum.Text = count.ToString();
  75. }

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

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

Or, use the Enumerable.Aggregate method instead.

  1. var count = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
  2. .Aggregate(0, (total, row) =&gt; total += row.Cells
  3. .Cast&lt;DataGridViewCell&gt;()
  4. .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.

  1. private Dictionary&lt;int, int&gt; ResultadoNumeros;
  2. private void calculaTotalGrid()
  3. {
  4. int outVal = 0;
  5. ResultadoNumeros = dgLista.Rows.Cast&lt;DataGridViewRow&gt;()
  6. .SelectMany(r =&gt; r.Cells.Cast&lt;DataGridViewCell&gt;()
  7. .Where(c =&gt; c.ColumnIndex &gt; 0 &amp;&amp; int.TryParse(c.Value?.ToString(), out outVal)))
  8. .GroupBy(c =&gt; int.Parse(c.Value.ToString()))
  9. .ToDictionary(x =&gt; x.Key, x =&gt; x.Count());
  10. foreach (var kvp in ResultadoNumeros)
  11. Console.WriteLine($&quot;{kvp.Key} -&gt; {kvp.Value}&quot;);
  12. }

To get the count of value 15 for example:

  1. int count15 = ResultadoNumeros[15];

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

  1. int outVal = 0;
  2. if (ResultadoNumeros.TryGetValue(15, out outVal))
  3. 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:

确定