LINQ syntax question

K

Kevin S. Goff

Someone asked me how I would do the following....suppose 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",typeof(Decimal));

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

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

var Results = from rowEmpData in dtEmps.AsEnumerable()
join rowNoteData in dtNotes.AsEnumerable()

on rowEmpData.Field<Int32>("EmployeeID") equals
rowNoteData.Field<Int32>("EmployeeID")
where rowEmpData.Field<decimal>("Salary") > 90000
select new (rowEmpData.AllColumns, rowNoteData.AllColumns);


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

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

Thanks,
Kevin
 
M

Marc Gravell

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.WriteLine("{0}, {1}, {2}",
result.Employee["EmployeeID"], result.Employee["Salary"],
result.Note["Notes"]);
}

Any use?

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top