• 热门专题

用LINQ对两个DataTable作Join查询

作者:Find My Way  发布日期:2013-07-12 10:58:01
Tag标签:LINQ  DataTable  
  • 个人觉得满好用的写法,可以减少不少的程序代码

    但是这方式是把两个Table的数据都捞出来后,再作Join比对

    效能上有疑虑,要注意一下

    希望后面会学到更有效的做法

    学习中~~

     

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Lab_LinqToDataSet
    {
        class Program
        {
            static void Main(string[] args)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Lab_LinqToDataSet.Properties.Settings.DemoDBConnectionString"].ToString());
                string sql1 = "select * from Books";
                string sql2 = "select * from Category";
                DataSet ds = new DataSet();
                using (conn)
                {
                    SqlDataAdapter da = new SqlDataAdapter(sql1, conn);
                    da.Fill(ds, "Books");
    
                    da = new SqlDataAdapter(sql2, conn);
                    da.Fill(ds, "Category");
                }
                DataTable dt1 = ds.Tables["Books"];
                DataTable dt2 = ds.Tables["Category"];
                
                var enumTable = from bookTable in dt1.AsEnumerable()
                                join categoryTable in dt2.AsEnumerable()
                                on bookTable.Field<int>("CategoryID") equals 
                                   categoryTable.Field<int>("ID")
                                where bookTable.Field<int>("Price") > 180
                                select new
                                {
                                    ISBN = bookTable.Field<string>("ISBN"),
                                    Title = bookTable.Field<string>("Title"),
                                    Price = bookTable.Field<int>("Price"),
                                    CateogryName = categoryTable.Field<string>("Name")
                                };
    
                string output = string.Empty;
                foreach (var bookRow in enumTable)
                {
                    output =
                        "\nISBN: " + bookRow.ISBN +
                        "\t书名: " + bookRow.Title +
                        "\t售价: " + bookRow.Price.ToString() +
                        "\t分类: " + bookRow.CateogryName;
                    Console.WriteLine(output);
                }
                
                Console.Read();
            }
        }
    }
    

     

About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规