用心计较般般错 安心自守事事宽

cgl 坚持、努力终有所获
  新随笔  :: 管理

LINQ、Lambda 的转换

Posted on 2016-01-02 22:28  用心计较般般错 安心自守事事宽  阅读(208)  评论(0编辑  收藏  举报
            var d = from d1 in pDT1.AsEnumerable()
                    from d2 in pDT2.AsEnumerable()
                    where d1.Field<string>("ID") == d2.Field<string>("ID")
                    select new { a = d1.Field<string>("ID"), v = d1.Field<double>("VALUE") * d2.Field<double>("VALUE") };
            var d = pDT1.AsEnumerable().Join(pDT2.AsEnumerable(), s => s.Field<string>("ID"), sc => sc.Field<string>("ID"), (s, sc) => new
            {
                a = s.Field<string>("ID"),
                v = s.Field<double>("VALUE") * sc.Field<double>("VALUE")
            });

 例子,三个DataTable之间的运算

            var d = pDT1.AsEnumerable().Join(pDT2.AsEnumerable(), s => s.Field<string>("ID"), sc => sc.Field<string>("ID"), (s, sc) => new
            {
                a = s.Field<string>("ID"),
                v = s.Field<double>("VALUE") * sc.Field<double>("VALUE")
            });
            DataTable pDT3 = pGetDT();
            foreach (var l in d)
            {
                DataRow pDR = pDT3.NewRow();
                pDR[0] = l.a;
                pDR[1] = l.v;
                pDT3.Rows.Add(pDR);
                Console.WriteLine("{0} {1}", l.a, l.v);
            }
            var E = from d1 in d
                    from d2 in pDT1.AsEnumerable()
                    where d1.a == d2.Field<string>("ID")
                    select new { a = d1.a, v = Convert.ToDouble( d1.v) - d2.Field<double>("VALUE") };

            foreach (var l in E)
            {
                Console.WriteLine("{0} {1}", l.a, l.v);
            }
            Console.ReadLine();