英文:
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<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();
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("Select * from TBLotofacil ORDER BY Concurso DESC", 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<DataGridViewRow>())
foreach (var cell in row.Cells.Cast<DataGridViewCell>())
count += int.TryParse(cell.Value?.ToString(), out int val) &&
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<DataGridViewRow>()
.SelectMany(r => r.Cells.Cast<DataGridViewCell>()
.Where(c => int.TryParse(c.Value?.ToString(), out int val) && val == valToCount))
.Count();
```"
"Or, use the [`Enumerable.Aggregate`][2] method instead.
```c#
var count = dgLista.Rows.Cast<DataGridViewRow>()
.Aggregate(0, (total, row) => total += row.Cells
.Cast<DataGridViewCell>()
.Count(c => c.Value != null && 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<int, int>` instead of the `ResultadoNumeros` class. This way, you don't need to repeat one of the previous solutions for each value.
```c#
private Dictionary<int, int> ResultadoNumeros;
private void calculaTotalGrid()
{
int outVal = 0;
ResultadoNumeros = dgLista.Rows.Cast<DataGridViewRow>()
.SelectMany(r => r.Cells.Cast<DataGridViewCell>()
.Where(c => c.ColumnIndex > 0 && int.TryParse(c.Value?.ToString(), out outVal)))
.GroupBy(c => int.Parse(c.Value.ToString()))
.ToDictionary(x => x.Key, x => x.Count());
foreach (var kvp in ResultadoNumeros)
Console.WriteLine($"{kvp.Key} -> {kvp.Value}");
}
```"
"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<TKey,TValue>.Keys][3] property.
+ [Dictionary<TKey,TValue>.ContainsKey(TKey)][4] method.
+ [Dictionary<TKey,TValue>.Values][5] property.
+ [Dictionary<TKey,TValue>.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&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&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&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&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&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&view=net-7.0"
<details>
<summary>英文:</summary>
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.
```c#
private void calculaTotalGrid()
{
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 int val) &&
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<DataGridViewRow>()
.SelectMany(r => r.Cells.Cast<DataGridViewCell>()
.Where(c => int.TryParse(c.Value?.ToString(), out int val) && val == valToCount))
.Count();
Or, use the Enumerable.Aggregate
method instead.
var count = dgLista.Rows.Cast<DataGridViewRow>()
.Aggregate(0, (total, row) => total += row.Cells
.Cast<DataGridViewCell>()
.Count(c => c.Value != null && 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<int, int>
instead of the ResultadoNumeros
class. This way, you don't need to repeat one of the previous solutions for each value.
private Dictionary<int, int> ResultadoNumeros;
private void calculaTotalGrid()
{
int outVal = 0;
ResultadoNumeros = dgLista.Rows.Cast<DataGridViewRow>()
.SelectMany(r => r.Cells.Cast<DataGridViewCell>()
.Where(c => c.ColumnIndex > 0 && int.TryParse(c.Value?.ToString(), out outVal)))
.GroupBy(c => int.Parse(c.Value.ToString()))
.ToDictionary(x => x.Key, x => x.Count());
foreach (var kvp in ResultadoNumeros)
Console.WriteLine($"{kvp.Key} -> {kvp.Value}");
}
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:
-
Dictionary<TKey,TValue>.Keys property.
-
Dictionary<TKey,TValue>.Values property.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论