日期:2014-05-20  浏览次数:21015 次

如何实现和sql一样的左连接效果


 //创建一个UserInfo的数据表
            DataTable dt = new DataTable("UserInfo");
            //添加id和username列
            dt.Columns.Add("id");
            dt.Columns.Add("username");
            //创建行
            DataRow dr = dt.NewRow();
            dr["id"] = 1;
            dr["username"] = "张三";
            dt.Rows.Add(dr);

            DataRow dr1 = dt.NewRow();
            dr1["id"] = 2;
            dr1["username"] = "李四";
            dt.Rows.Add(dr1);

            dt.Rows.Add("3", "王五");

 DataTable detailInfo = new DataTable("detailInfo");
            detailInfo.Columns.Add("ID");
            detailInfo.Columns.Add("phoneNumber");
            detailInfo.Columns.Add("addRess");

            detailInfo.Rows.Add("1", "135XXXX", "北京");
            detailInfo.Rows.Add("2", "136XXXX", "上海");
            detailInfo.Rows.Add("5", "186XXXX", "广州");

            Console.WriteLine("2个表进行合并");

            var query = from t1 in dt.AsEnumerable()
                        join t2 in detailInfo.AsEnumerable()
                        on t1.Field<string>("id") equals t2.Field<string>("ID")
                        select new
                            {
                                id = t1.Field<string>("id"),
                                username = t1.Field<string>("username"),
                                phoneNumber = t2.Field<string>("phoneNumber"),