本文介绍了如何使用LINQ创建总计列和总计行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个没有总计列或行的数据表.如何使用LINQ添加总计列"和总计行"以创建下表?

Given a datatable that does not have a total column or row. How can I use LINQ to add a Total Column and Total row to create the table below?

TextColumn, NumberColumn0, NumberColumn1 Total
A                1              4          5
B                2              55         47
C                2.3            DBNULL     2.3
D                4              3          7
Total            9.3            62         61.3

谢谢!

嗯,对于那些需要代码的人.我目前正在使用此列作为总计列:

Um, for those who need code. I'm using this currently for total column:

public static void CreateTotalColumnByType(DataTable table, Type valueType)
{
    // create expression
    string expression = string.Empty;

    // do not count the first column (used for string field)
    for (int columnIndex = 1; columnIndex < table.Columns.Count; ++columnIndex)
    {
        if (columnIndex != table.Columns.Count - 1)
        {
            // add +
            expression += String.Format("[{0}] + ", table.Columns[columnIndex].ColumnName);
        }
        else
        {
            // last column so don't add plus
            expression += String.Format("[{0}]", table.Columns[columnIndex].ColumnName);
        }
    }

    // add total column
    DataColumn totalColumn = new DataColumn("Total", valueType, expression);
    table.Columns.Add(totalColumn);
}

但是我想用LINQ代替它.

but I'd like to replace it with LINQ.

推荐答案

//adds Total column
var q1 = src.Select(x=>new { x.TextColumn
                            ,x.NumberColumn0
                            ,x.NumberColumn1
                            ,Total=x.NumberColumn0+x.NumberColumn1});

//adds Totals row
var q2 = q1.Concat(new[]{new{ TextColumn="Total"
                             ,NumberColumn0 = src.Sum(_=>_.NumberColumn0)
                             ,NumberColumn1 = src.Sum(_=>_.NumberColumn1)
                             ,Total=q1.Sum(_=>_.Total)}});

这篇关于如何使用LINQ创建总计列和总计行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 04:13