简体   繁体   English

Linq into子句仅返回联接表中的列

[英]Linq into clause returning only columns from joined table

I joined a 2 data tables based on the EMP column and used copytodatatable, however when i load the new datatable into datagridview it only shows the joined columns(salarydt) from the query, why is this?? 我加入了一个基于EMP列的2个数据表,并使用了copytodatatable,但是当我将新数据表加载到datagridview时,它仅显示查询中的合并列(salarydt),这是为什么?

 var collection = from p in dt.AsEnumerable()
                         join q in salaryDT.AsEnumerable() on p.Field<int>("Emp") equals q.Field<int>("Emp1") into UP
                         from t in UP
                         select t;
 DataTable resultdt = new DataTable();
 dt = collection.CopyToDataTable();

DataTable itself is perfectly geared to merging itself with another data table, using its, well, Merge method. DataTable本身非常适合使用其Merge方法与另一个数据表Merge Here's a litte example: 这是一个小例子:

var dt1 = new DataTable("a");
dt1.Columns.Add("ID", typeof(int));
dt1.Columns.Add("Item1", typeof(int));
dt1.PrimaryKey = new[] { dt1.Columns[0] };

var dt2 = new DataTable("a");
dt2.Columns.Add("ID", typeof(int));
dt2.Columns.Add("Item2", typeof(int));
dt2.PrimaryKey = new[] { dt2.Columns[0] };


for (int i = 0; i < 10; i++)
{
    dt1.Rows.Add(new object[] { i, i });
    dt2.Rows.Add(new object[] { i, i + 10 });
}

dt1.Merge(dt2);

Now dt1 has three columns, ID , Item1 , and Item2 . 现在, dt1具有三列IDItem1Item2

ID  Item1   Item2
0   0       10
1   1       11
2   2       12
3   3       13
4   4       14
5   5       15
6   6       16
7   7       17
8   8       18
9   9       19

Maybe what you should to do is just return a custom list of items: 也许您应该做的只是返回自定义项目列表:

Option 1 选项1

var data = new Employee[] { new Employee { Id = 1, Name = "John Doe" } };

var data2 = new Salary[] { new Salary { Id = 1, Wage = "$ 50,000.00" } };

var collection = from p in data
                   join q in data2 on p.Id equals q.Id              
                   select new { Id = p.Id, Name = p.Name, Wage = q.Wage };

Please check the example: link 请检查示例: 链接

Option 2 选项2

var data = new Employee[] { new Employee { Id = 1, Name = "John Doe" } };

var data2 = new Salary[] { new Salary { Id = 1, Wage = "$ 50,000.00" } };

var collection = from p in data
                   join q in data2 on p.Id equals q.Id              
                   select new { p, q };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM