locked
Query to Select Values From Two Tables Into One Column

    Question

  • Hi,

    I can not seem to get my head around how to do this.  I have two queries which return distinct results.  The second query define children of the first query. I would like to create a third query which combines values from each of the first two queries in to a single column.

    For Example -
    Query 1 yields:
    Parent
    100
    130
    150
    160
    200

    Query 2 yields:
    Parent  Child
    100      110
    100      120
    130      140
    160      190

    I want a query 3 to yield:
    100
    110
    120
    130
    140
    150
    160
    190
    200

    Thanks in advance for any help,
    Ryan

    Friday, September 18, 2009 9:46 PM

Answers

  • Hi,

    Could you please be more specific about the query? Is it query from datatable.

    You might want to use Union to get the result, the code below retrieve one column of the rows in two tables:

                DataTable dt1 = new DataTable();

                dt1.Columns.Add("Parent", typeof(int));

                dt1.Rows.Add(100);

                dt1.Rows.Add(130);

                dt1.Rows.Add(150);

                dt1.Rows.Add(160);

                dt1.Rows.Add(200);

     

                DataTable dt2 = new DataTable();

                dt2.Columns.Add("Parent", typeof(int));

                dt2.Columns.Add("Child", typeof(int));

                dt2.Rows.Add(100, 110);

                dt2.Rows.Add(100, 120);

                dt2.Rows.Add(130, 140);

                dt2.Rows.Add(160, 190);

     

                var query = dt1.AsEnumerable().Select(r => r.Field<int>("Parent")).Union(dt2.AsEnumerable().Select(r => r.Field<int>("Parent"))).

                    Union(dt2.AsEnumerable().Select(r => r.Field<int>("Child"))).OrderBy(i => i);

     

                foreach (var q in query)

                {

                    Console.WriteLine(q);

                }

    Harry


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    • Marked as answer by Harry Zhu Friday, September 25, 2009 3:43 AM
    Tuesday, September 22, 2009 9:09 AM