• 00
  • :
  • 00
  • :
  • 00

DataTable Group By或运算 Linq Aggregate的使用

 class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(System.String));
            dt.Columns.Add("Value", typeof(System.Int32));

            dt.Rows.Add("07", 1);
            dt.Rows.Add("07", 2);
            dt.Rows.Add("07", 4);
            dt.Rows.Add("07", 8);
            dt.Rows.Add("07", 4);

            dt.Rows.Add("08", 2);
            dt.Rows.Add("08", 8);
            dt.Rows.Add("08", 16);
            dt.Rows.Add("08", 8);
            dt.Rows.Add("08", 16);

            var query = from t in dt.AsEnumerable()
                        group t by new { Name = t.Field<string>("Name") } into m
                        select new
                        {
                            Name = m.Key.Name,
                            Sum = m.Sum(n => n.Field<int>("Value")),
                            CustomerValue = m.Aggregate(0, (d, n) =>
                            {
                                return d | n.Field<int>("Value");
                            })
                        };

            query.ToList().ForEach(p =>
            {
                Console.WriteLine($"Name:{p.Name}\tSum:{p.Sum}\tCustomerValue:{p.CustomerValue}");
            });
            Console.ReadKey();
        }
    }

 

posted @ 2017-05-06 13:19  Garson_Zhang  阅读(438)  评论(0编辑  收藏  举报