LINQ syntax question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kevin S. Goff

    LINQ syntax question

    Someone asked me how I would do the following....su ppose you have two
    ADO.NET datatables, and you want to do the equivalent of SELECT
    Table1.*, Table2.* (in other words, do a linq query that joins the
    two, and brings in all columns).

    For instance...

    DataTable dtEmps = new DataTable();
    dtEmps.Columns. Add("EmployeeID ", typeof(Int32));
    dtEmps.Columns. Add("Salary",ty peof(Decimal));

    dtEmps.Rows.Add (1,90000);
    dtEmps.Rows.Add (2,80000);
    dtEmps.Rows.Add (3,95000);

    DataTable dtNotes = new DataTable();
    dtNotes.Columns .Add("EmployeeI D", typeof(Int32));
    dtNotes.Columns .Add("Notes", typeof(String)) ;
    dtNotes.Rows.Ad d(1, "Notes 1 for Kevin S. Goff");
    dtNotes.Rows.Ad d(1, "Notes 2 for Kevin S. Goff");
    dtNotes.Rows.Ad d(2, "Notes 1 for Steve Goff");
    dtNotes.Rows.Ad d(3, "Notes 1 for Gwen Goff");

    var Results = from rowEmpData in dtEmps.AsEnumer able()
    join rowNoteData in dtNotes.AsEnume rable()

    on rowEmpData.Fiel d<Int32>("Emplo yeeID") equals
    rowNoteData.Fie ld<Int32>("Empl oyeeID")
    where rowEmpData.Fiel d<decimal>("Sal ary") 90000
    select new (rowEmpData.All Columns, rowNoteData.All Columns);


    My only answer is just to list all the columns in the select...select
    new { RowEmpData.Fiel d<Int32>("Emplo yeeID"), etc.)

    Is there a shortcut to pull all columns from both data tables?

    Thanks,
    Kevin




  • Marc Gravell

    #2
    Re: LINQ syntax question

    Is there a shortcut to pull all columns from both data tables?

    How about:
    select new { Employee = rowEmpData, Note = rowNoteData };

    This gives you all the data, without having to worry about name
    conflicts like "EmployeeID " in each. It is also clear what comes from
    where - essentially acting as the alias in SQL:

    foreach (var result in results) {
    Console.WriteLi ne("{0}, {1}, {2}",
    result.Employee["EmployeeID "], result.Employee["Salary"],
    result.Note["Notes"]);
    }

    Any use?

    Marc

    Comment

    Working...