Click here to Skip to main content
15,843,623 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
i have 2 linq dataclasses connecting 2 DBs with same fields and tables but different aliases.
i want to use union with 2 queries from both of my DBs.
how can i do that?
my code is:

C#
var q1 = from t1 in db1.tbTeacher1s
                    select new
                    {
                        tId = t1.tId1,
                        tFullName = t1.tName1 + " " + t1.tFamily1,
                        Branch = 1
                    };
           var q2 = from t2 in db2.tbTeacher2s
                    select new
                    {
                        tId = t2.tId2,
                        tFullName = t2.tName2 + " " + t2.tFamily2,
                        Branch = 2
                    };
           var q3 = (q1).Union(q2);
           rptTeachers.DataSource = q3;
           rptTeachers.DataBind();
Posted

1 solution

Use the below code:

public class UnionObjects
    {
        public static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Column1");
            dt.Columns.Add("Column2");

            DataRow dr = dt.NewRow();
            dr["Column1"] = "Col Val -1";
            dr["Column2"] = "Col2 Val -1";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Column1"] = "Col Val -2";
            dr["Column2"] = "Col2 Val -2";
            dt.Rows.Add(dr);

            DataTable dtc = dt.Clone();
            dr = dtc.NewRow();
            dr["Column1"] = "Col Val -3";
            dr["Column2"] = "Col2 Val -3";
            dtc.Rows.Add(dr);

            dr = dtc.NewRow();
            dr["Column1"] = "Col Val -4";
            dr["Column2"] = "Col2 Val -4";
            dtc.Rows.Add(dr);

            dt.AcceptChanges();
            dtc.AcceptChanges();

            var query1 = from row in dt.AsEnumerable()
                         select row;
            var query2 = from row in dtc.AsEnumerable()
                         select row;

            IEnumerable<DataRow> rowCollection = query1.Union(query2);

            DataTable dtNew = dt.Clone();
            foreach (DataRow row in rowCollection)
                dtNew.ImportRow(row);

            foreach (DataRow row in dtNew.Rows)
                Console.WriteLine(string.Format("{0} -- {1}", row["Column1"].ToString(), row["Column2"].ToString()));
            Console.Read();

        }
    }



Thanks
 
Share this answer
 
v2
Comments
Pooyan Behroozfar 27-Mar-14 1:59am    
do u have any solutions without datatables?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900