[英]Using LINQ, how can I get a joined table returned as IEnumerable<DataRow>
I use SQL a lot, and I'm trying to transfer the same joining logic to LINQ queries against a DataSet. 我经常使用SQL,并且尝试将相同的联接逻辑传递给针对DataSet的LINQ查询。 The DataSet is a bunch of tables which are pulled from SQL queries further up the line.
DataSet是一堆表,这些表从SQL查询中进一步拉出。
I managed to get this join working - 我设法使这种加入有效-
IEnumerable<DataRow> query =
from a in ds.Tables["Names"].AsEnumerable()
join b in ds.Tables["NameHasAffiliate"].AsEnumerable()
on a.Field<int>("PK") equals b.Field<int>("fk_MainTable_PK")
select a;
This doesn't compile: 这不会编译:
select a.Field<int>("PK"), a.Field<string>("Name")
and nor does 而且也不
select new { PK = a.Field<int>("PK"), Name = a.Field<string>("Name") }
It's definitely querying correctly (I see the expected amount of rows and duplicated table a
data) but this is only returning the table a
columns - obviously because of select a
. 这肯定正确的查询(我看行的预期量和重复表
a
的数据),但是这仅仅是返回表a
列-显然,因为select a
。
I've tried changing to select new { a, b }
and also wrapping the query up in ()
to add an .ToList()
at the end, but neither compiles to give me the IEnumerable version of the query for a simple converstion to table aftewards using 我尝试更改以
select new { a, b }
并将查询也包装在()
以在末尾添加.ToList()
,但是都没有编译以提供查询的IEnumerable版本来进行简单对话桌子偏爱使用
DataTable boundTable = query.CopyToDataTable<DataRow>();
How can I select ALL the columns like this? 如何选择所有这样的列? Or rather, if I'm joining a lot of tables, how can I specify which columns from each table?
或者说,如果我要联接很多表,如何指定每个表中的哪些列?
This is because returning anything other than a DataRow
will not work in your example, since you are defining the query to be of type IEnumerable<DataRow>
. 这是因为在您的示例中,返回除
DataRow
之外的任何内容均无效,因为您将查询定义为IEnumerable<DataRow>
类型。 So if you are returning a field or collection of fields, then you need to change the expected return type. 因此,如果要返回一个字段或字段集合,则需要更改期望的返回类型。
I tried the following and it works just fine. 我尝试了以下方法,但效果很好。
var ds = new DataSet();
ds.Tables.Add("Names");
ds.Tables["Names"].Columns.Add("PK", typeof(Int32));
ds.Tables["Names"].Columns.Add("Name", typeof(String));
ds.Tables["Names"].Rows.Add("1", "NameValue1");
ds.Tables.Add("NameHasAffiliate");
ds.Tables["NameHasAffiliate"].Columns.Add("fk_MainTable_PK", typeof(Int32));
ds.Tables["NameHasAffiliate"].Columns.Add("AffiliateValue", typeof(String));
ds.Tables["NameHasAffiliate"].Rows.Add("1", "AffiliateValue1");
var query =
ds.Tables["Names"].AsEnumerable()
.Join(
ds.Tables["NameHasAffiliate"].AsEnumerable(),
n => n.Field<int>("PK"), a => a.Field<int>("fk_MainTable_PK"),
(n, a) => new { Key = n.Field<Int32>("PK"), Name = n.Field<String>("Name")})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.