【註: 沒營養的老人備忘筆記系列又來了,熱血青年請自行迴避。】

以下範例展示如何利用.NET DataColumn.Expression自動計算百分比: (適用: Mini C# Lab)

using System;
using System.IO;
using System.Threading;
using System.Data;
//REFDLL System.Data;System.Xml
public class CSharpLab
{
    public static void Test()
    {
        DataTable t = new DataTable();
        t.Columns.Add("CatgName", typeof(string));
        t.Columns.Add("Amount", typeof(int));
        t.Columns.Add("Percentage", typeof(float)).Expression
            = "Amount / IIF(Sum(Amount) > 0, Sum(Amount), 1)";
        t.Rows.Add("PC", 200);
        t.Rows.Add("NB", 300);
        t.Rows.Add("PDA", 500);
        foreach (DataRow r in t.Rows)
            Console.WriteLine("{0}: {1:P}", 
                r["CatgName"], r["Percentage"]);
    }
}

執行結果如下:

Built successfully in 254ms!
Prepare to run...
==================================================
PC: 20.00%
NB: 30.00%
PDA: 50.00%

==================================================
Execution time: 2 ms

【2009/08/13更新】Expression加入IIF判斷,防止SUM()==0會發生除以零的狀況。


Comments

# by nj

請問如果是從資料庫讀出資料後直接轉入datatable,該如何套用此種做法做加總? thx

# by jack

請問如果是從資料庫讀出資料後直接轉入datatable,該如何套用此種做法做加總? thx

# by Jeffrey

to Jack, 事實上,我的實際應用就是由DB查詢取出DataTable後再加工。DataTable t = new DataTable(); myDataAdapter.Fill(dt); dt.Columns.Add("Percentage", typeof(decimal)).Expression("col1 / SUM(col1)"; 這樣就可以了。

Post a comment