【问题标题】:Calculate percentage from datagridview data with linq query使用 linq 查询从 datagridview 数据中计算百分比
【发布时间】:2021-08-13 11:46:08
【问题描述】:

我使用这个 linq 查询对 datagridview 中的一些值进行分组和计算。

var Sums = dataGridView1.Rows.Cast<DataGridViewRow>()
          .Where(row => row.Cells[8].Value != null)
        .GroupBy(row => row.Cells[8].Value.ToString()) 

        .Select(g => new { Gruppo = g.Key, Serie = g.Sum(row => Convert.ToInt32(row.Cells[2].Value)) });

如何在每组和总数之间添加百分比计算来改进这一点?

我想要的是,如果“Serie”列值的总和为 20(例如),在第三列中我看到 3(第一个单元格中的值)是 15% 等。

【问题讨论】:

  • 对于我使用的数据源:dataGridView.DataSource = Sums.ToList();问题是,对于我用来计算百分比的任何代码,我得到的结果都是 0
  • @JohnG 我发现了问题。我将 linq 查询从 Convert.ToInt 更改为 Convert.ToDecimal 并得到正确的结果,然后我使用 dataGridView1.Columns["Percent"].DefaultCellStyle.Format = "0.00'%'";从您的答案中得出结果。谢谢!

标签: c# linq datagridview


【解决方案1】:
Sums = dataGridView1.Rows.Cast<DataGridViewRow>()
        .Where(row => row.Cells[8].Value != null)
        .GroupBy(row => row.Cells[8].Value.ToString()) 
        .Select(g => new 
            { 
                Gruppo = g.Key,
                Serie = g.Sum(row => Convert.ToInt32(row.Cells[2].Value)),
                Percente = (g.Sum(row => Convert.ToInt32(row.Cells[2].Value)) / Convert.ToInt32(label15.Text)) * 100
            });

【讨论】:

  • 这给了我同样的结果。我想要做的是在第三列中设置值之间的百分比
  • @Gabriele 您想知道,例如,“glutei”在所有组中的百分比是多少,并将其包含在结果中?
  • 是的,所以在上面的示例中,如果值的总和为 20,则 glutei 为 15%,因为值为 3
  • 我不知道你可以在一个 LINQ 行中做到这一点,因为你必须得到总值。你不会知道,直到它完成。也许你可以,但它看起来很脏
  • 我有一个标签中的总值,所以我可以从:Convert.ToInt32(label15.Text)。既然我有了总数,我该怎么做呢?
猜你喜欢
  • 2011-09-06
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2012-05-01
  • 2014-04-06
  • 1970-01-01
相关资源
最近更新 更多