使用.Select()。Join()联接两个数据表

时间:2018-06-28 01:36:19

标签: c# linq join datatable

我一直在高空搜寻,但无济于事。我有两个数据表,我想加入而不创建新的结果表,因为我只需要更新其中一个表中的某些行以显示在网格视图中即可,类似于下面的代码,但是加入:

sage_invoices.Select("CCE2 IS NULL")
                .ToList<DataRow>()
                .ForEach(row =>
                {
                    row["Error"] = 1;
                    row["ErrorMessage"] = "Missing Region Code (Dimension 2 - CCE2)";
                });

我发现的所有内容都会产生一个新的输出数据表,类似于下面的代码:

var collection = from t1 in dt1.AsEnumerable()
         join t2 in dt2.AsEnumerable()
         on t1["id"] equals t2["id"]
         select new { T1 = t1, T2 = t2 };

我找不到如何使用.Join连接两个DataTables:

sage_invoices.Select()
                .Join(<What Goes here?>)
                .ToList<DataRow>()
                .ForEach(row =>
                {
                    row["Error"] = 1;
                    row["ErrorMessage"] = "ITMREF is not a Sage Product Code";
                });

如果有人能指出我正确的方向,我将不胜感激。

谢谢 加雷斯

1 个答案:

答案 0 :(得分:1)

通常,我通过构建一个匿名对象来实现此目的,该匿名对象包含一个通过Join或GroupJoin对我的源对象和目标对象的引用,然后遍历Join的结果以更新我的目标对象。请参见下面的示例。

看看JoinGroupJoin上的文档。 Join适用于1-1匹配,而GroupJoin适用于0- *匹配(如SQL左连接)。 Join和GroupJoin的参数允许您为每个IEnumerable指定一个选择器函数,然后为输出对象指定一个选择器函数。请注意,下面的t1t2指的是table1table2

using System;
using System.Data;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var table1 = GetEmptyTable();
        table1.Rows.Add(1, "Old Value", false);
        table1.Rows.Add(2, "Untouched Value", false);

        var table2 = GetEmptyTable();
        table2.Rows.Add(1, "New Value", false);
        table2.Rows.Add(3, "Unused Value", false);

        Console.WriteLine("Before...");
        Console.WriteLine(PrintTable(table1));

        var matched = table1.Select()
            .Join(table2.Select(), t1 => (int)t1["A"], t2 => (int)t2["A"], (t1, t2) 
=> new
            {
                DestinationRow = t1,
                SourceRow = t2
            });
        foreach (var match in matched)
        {
            match.DestinationRow["B"] = match.SourceRow["B"];
            match.DestinationRow["C"] = true;
        }

        Console.WriteLine("After...");
        Console.WriteLine(PrintTable(table1));
    }

    private static DataTable GetEmptyTable()
    {
        var table = new DataTable();
        table.Columns.Add("A", typeof(int));
        table.Columns.Add("B", typeof(string));
        table.Columns.Add("C", typeof(bool));
        return table;
    }

    private static string PrintTable(DataTable table)
    {
        return string.Join(Environment.NewLine, table.Select().Select(x => "[" + 
string.Join(", ", x.ItemArray) + "]"));
    }
}
相关问题