星期二, 9月 23, 2014

[LINQ] 累計加總

之前是利用 T-SQL 作到,這次是用 LINQ 來練習
namespace LINQRunningTotal
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
   
            int LINQQty = 0;
            var LINQSource = (from data in getData().AsEnumerable()
                                orderby data.Field<int>("Qty") descending
                                select new
                                {
                                    Question = data.Field<string>("Question"),
                                    Qty = data.Field<int>("Qty"),
                                    RuningTotal = (LINQQty += data.Field<int>("Qty"))
                                }).ToList();

            int LamdbaQty = 0;
            var LamdbaSource = getData().AsEnumerable().
                OrderByDescending(data => data.Field<int>("Qty")).
                Select
                (data =>
                {
                    LamdbaQty += data.Field<int>("Qty");
                    return new
                    {
                        Question = data.Field<string>("Question"),
                        Qty = data.Field<int>("Qty"),
                        RunningTotal = LamdbaQty
                    };
                }
                ).ToList();

            dgvData.DataSource = LamdbaSource;
        }

        private DataTable getData()
        {
            DataTable dt = new DataTable("ParetoChart");
            dt.Columns.Add("Question", typeof(string));
            dt.Columns.Add("Qty", typeof(int));
            dt.Columns.Add("RunningTotal", typeof(int));
            dt.Rows.Add("馬達運轉異常", 38, 0);
            dt.Rows.Add("馬達異音", 22, 0);
            dt.Rows.Add("運輸撞傷", 6, 0);
            dt.Rows.Add("鰭片間距不良", 0, 0);
            dt.Rows.Add("銅管凹陷", 2, 0);
            dt.Rows.Add("組裝不良", 17, 0);
            dt.Rows.Add("洩漏", 3, 0);
            return dt;
        }
    }
}
[LINQ] 累計加總

沒有留言:

張貼留言