c# - 执行表连接后在 C# 中处理 lambda 查询结果
问题描述
所以我有一个将两个数据表连接在一起的查询:
var results = (
from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on
new { a = t1["col1"], b= t1["col2"], c = t1["col3"] } equals
new { a= t2["col1"], b= t2["col2"], c= t2["col3"] }
into joinedComboTable
select joinedComboTable);
它产生一个类型为IEnumerable<IEnumerable<datarow>>"
我如何将其转换为DataTable
?表 1 和表 2 是 C# DataTable
。我确实看到了 304 个结果,我可以通过调试器和我拥有的 results.inner (Non-Public) 参数看到这些结果,DataColumn
并且我可以看到 304 行。但我无法弄清楚如何获得实际结果并将其保存到DataTable
.
更新:2020.01.23 @ 9:04pm
所以,我检查了下面的几个选项,当我执行 results.ToList() 时,我基本上得到了一个包含 304 个条目的列表,但每一行的值都是 System.Data.DataRow[0]。我肯定错过了什么....
对此进行迭代不会产生预期的结果。
解决方案
尝试这个
static void Main(string[] args)
{
var table1 = new DataTable();
table1.Columns.Add("col1", typeof(string));
table1.Columns.Add("col2", typeof(string));
table1.Columns.Add("col3", typeof(string));
table1.Columns.Add("col4", typeof(string));
var row = table1.NewRow();
row["col1"] = "1";
row["col2"] = "1";
row["col3"] = "1";
row["col4"] = "something different";
table1.Rows.Add(row);
row = table1.NewRow();
row["col1"] = "2";
row["col2"] = "2";
row["col3"] = "2";
row["col4"] = "something different";
table1.Rows.Add(row);
var table2 = new DataTable();
table2.Columns.Add("col1", typeof(string));
table2.Columns.Add("col2", typeof(string));
table2.Columns.Add("col3", typeof(string));
table2.Columns.Add("col4", typeof(string));
row = table2.NewRow();
row["col1"] = "1";
row["col2"] = "1";
row["col3"] = "1";
row["col4"] = "Another different thing";
table2.Rows.Add(row);
var results = (
from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on
new { a = t1["col1"], b = t1["col2"], c = t1["col3"] } equals
new { a = t2["col1"], b = t2["col2"], c = t2["col3"] }
into joinedComboTable
select joinedComboTable).ToList();
//Result
var newTable = results.FirstOrDefault()?.CopyToDataTable();
//However to get col4 form table 2 you need to do this
var result2 = (
from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on
new { a = t1["col1"], b = t1["col2"], c = t1["col3"] } equals
new { a = t2["col1"], b = t2["col2"], c = t2["col3"] }
select new { a = t1["col1"], b = t1["col2"], c = t1["col3"], d = t1["col4"], e = t2["col4"] });
//Result
var newTable2 = table1.Clone();
newTable2.Columns.Add("col4FromTable2", typeof(string));
foreach (var x1 in result2)
{
var r = newTable2.NewRow();
r["col1"] = x1.a;
r["col2"] = x1.b;
r["col3"] = x1.c;
r["col4"] = x1.d;
r["col4FromTable2"] = x1.e;
newTable2.Rows.Add(r);
}
}
推荐阅读
- ios - Swift Firebase“对象.....不存在”但图片保存到存储但不保存到数据库
- jquery - 将鼠标悬停在图像上后,如何在 jQuery 中“撤消”动画?
- database - 在 liquibase.properties 中设置几个“ChangeLogFile”值
- ios - 关闭或滑出应用程序时未触发iOS Objective-C didReceiveRemoteNotification
- java - dcoder 中 hello world 教程的问题
- c - 如何找到没有重复的n个整数的未排序数组A的重复并证明它
- php - 为什么 PHP 对 where 子句的处理方式与 phpmyadmin 不同?
- amazon-web-services - 使用 CLI 创建弹性 beanstalk 环境时如何指定自定义亚马逊机器映像 (AMI) ID?
- python - pandas - 将具有多种日期格式的列转换为日期时间
- python - datetime.strptime 格式