c#使用linq查询获取多个datagridview列值的总和

kyxcudwk  于 2023-11-14  发布在  C#
关注(0)|答案(1)|浏览(238)

我试图计算datagridview中多个列的总和,然后得到平均值。
此列包含一些值,如“3x8”(用于锻炼训练),我想计算多个列的第一个值(3)的总和
唯一的结果就是得到一个字符串的和,所以如果第一列是3x8,第二列是3x8,结果是33,当然,我想得到6。
下面是我的datagridview示例:

Group   Val1 to sum    Val2 to sum
-------------------------------------
group1       3x8              3x8
-------------------------------------
group1       1x5              5x5
-------------------------------------
group3       2x20             2x10
-------------------------------------

字符串
下面是我使用的代码:

var Su = dataGridView1.Rows.Cast<DataGridViewRow>()
      .Where(row => row.Cells["Group"].Value != null)
      .Where(row => row.Cells["Val1"].Value != null)
      .GroupBy(row => row.Cells["Group"].Value.ToString())
    .Select(g => new
    {
        Group = g.Key,
        Sum = g.Sum(row => {
            int sum = 0;
            if (row.Cells["week1"].Value.ToString().Contains("x"))
            {
                Debug.WriteLine("true condition 1");
                sum += (Convert.ToInt32(row.Cells[1].Value.ToString().Split('x')[0] + row.Cells[2].Value.ToString().Split('x')[0])) ;
                return sum;
            }
            else {
                Debug.WriteLine("true else");
                return 0; }
        })


有办法吗?

xlpyo6sf

xlpyo6sf1#

你只需要解析单元格的内容以符合你的0x0模式,然后将解析的数字相加。有很多方法可以做到这一点。如果它不是datagridviewrows,而只是一个数据数组,它可能看起来像这样,很多变体如下:

var gridsRows = new ITuple[] { // using value tuples
            ("group1", "3x8", "3x8"),
            ("group1", "1x5", "5x5"),
            ("group3",  "2x20", "2x10"),
            ("group4",  "14x4", "-")
        };  
    
     var parser = new Regex (@"^\s*(\d+)x\d+\s*$", RegexOptions.Compiled);

     var groupedSums = new Dictionary<string, int>(gridsRows
                .GroupBy(row => (string)row[0], (key, rows) => new KeyValuePair<string, int>(key, 
                         rows.Sum(r => ValOrZero(1, r) + ValOrZero(2, r)))));
          
      foreach (var sum in groupedSums)
          Console.WriteLine("{0}: {1,4}", sum.Key, sum.Value);

      /* Prints:
        group1:   12
        group3:    4
        group4:   14
      */
        
      int ValOrZero(int columnIndex, ITuple row) {
            return row[columnIndex] is string val
                && parser.Match(val) is { Success: true} m
            ?  int.Parse(m.Groups[1].Value) : 0;
      }

字符串
“翻译”回WinForms DataGridView(和C# 7.3 langver):

var parser = new Regex (@"^\s*(\d+)x\d+\s*$", RegexOptions.Compiled);

 var groupedSums = new Dictionary<string, int>( dataGridView1.Rows.Cast<DataGridViewRow>()
  .Where(row => row.Cells[0].Value != null)
  .Where(row => row.Cells[1].Value != null)
            .GroupBy(row => row.Cells[0].Value.ToString(), (key, rows) => new KeyValuePair<string, int>(key, 
                     rows.Sum(r => ValOrZero(row.Cells[1]) + ValOrZero(row.Cells[2])))));
      
  foreach (var sum in groupedSums)
      Console.WriteLine("{0}: {1}", sum.Key, sum.Value);
    
  int ValOrZero(DataGridViewCell cell) {
        return cell.Value?.ToString() is {} val
            && parser.Match(val) is var m && m.Success
        ?  int.Parse(m.Groups[1].Value) : 0;
  }

相关问题