【问题标题】:Show differences between two DataTables in C# with LINQ使用 LINQ 在 C# 中显示两个数据表之间的差异
【发布时间】:2017-04-28 11:57:57
【问题描述】:

我需要在 C# 中显示两个 DataTable 之间的差异。假设我有两个数据表

表 1

id       Name           Amount    Address      
1        Product1       500       ad1
2        Product2       600       ad2 
3        Product3       700       ad3
4        Product4       800       ad4

表 2

id       Name           Amount    Address      
1        Product1       600       ad1 
2        Product3       700       ad2
3        Product4       800       ad4

所以差异看起来像这样: 1个产品的金额不同,产品2在表2中不可见,产品3的地址不同,产品4相同。 所以表 3 应该是这样的

表 3

id       Name           Amount    Address      
1        Product1       600       ad1 
2        Product3       700       ad2
2        Product2       600       ad2 

如何使用 LINQ 查询来实现这一点?我看到的例子很少,但似乎我并没有完全理解它,其中很多仅适用于 1 列。 ID对我来说并不重要

【问题讨论】:

  • 显示您尝试过的内容以及您遇到的问题。
  • 你试过什么??你对不同的定义似乎很奇怪,因为它们看起来都不同吧产品 4...所以,具体一点,尝试向我们展示你在哪里做了什么,你得到了什么,并说出你为什么不满意,以及你没有得到什么
  • 我只想显示所有具有不同值的行。因此,如果我在具有不同地址的两个数据表中有 Product1,我想将此行添加到第三个数据表。

标签: c# wpf linq datatable


【解决方案1】:

一些连接应该这样做:

var result = from p1 in table1 
    join p2 in table2 on p1.Name equals p2.Name
    where p1.Amount != p2.Amount || p1.Address != p2.Adress
    select new Product { Name = p1.Name, Amount = p1.Amount, Adress = p1.Adress }

或者,您也可以在您的 Product 类(或无论如何调用它)上实现 Equals 以简化 where 子句:

class Product
{
    public override bool Equals(object other)
    {
        var p = other as Product;
        if (p == null) return false;
        return this.Name == p.Name && this.Address == p.Address && this.Amount == p.Amount;
    }
}

where p1.Equals(p2)

【讨论】:

  • CS1936 找不到源类型“DataTable”的查询模式的实现。
【解决方案2】:

你可以试试这个:

        // modified and new products
        var result = table2
                    .Select(d2 => new { d2.Product, d2.Amount, d2.Address })
                    .Except(table1.Select(d1 => new { d1.Product, d1.Amount, d1.Address }));

        var deletedProducts = table1
                             .Where(d => !table2.Select(d2 => d2.Product).Contains(d.Product))
                             .Select(d1 => new { d1.Product, d1.Amount, d1.Address });

        result = result.Concat(deletedProducts);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2017-11-02
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多