数据表,除了,c#

Datatables, Except, c#

我有两个数据表

Datatable A; //has a primany key ID
Datatable B; // has a primary key ID

我想要 A 和 B 的差值(A 减去 B)。在 C# 中使用 except 运算符时,except 对什么参数起作用? 我想根据主键区分A和B。

documentation正是您所需要的:

IEqualityComparer

If you want to compare sequences of objects of some custom data type, you have to implement the IEqualityComparer generic interface in a helperclass.

您可以使用自己的比较器进行比较,并且只使用一列或一组列。

public class ProductA
{ 
    public string Name { get; set; }
    public int ID { get; set; }
}

public class ProductComparer : IEqualityComparer<ProductA>
{

    public bool Equals(ProductA x, ProductA y)
    {
        //Check whether the objects are the same object. 
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether the products' properties are equal. 
        return x.ID== y.ID;
    }

    public int GetHashCode(ProductA obj)
    {
        //Get hash code for the ID field. 
        return obj.Code.GetHashCode();
    }
}


SourceA.Except(SourceB) 将为您提供源 A 中但不在源 B 中的所有内容


SourceB.Except(SourceA) 则相反。

或者您可能正在寻找 Full Outter Join!

这是完整的代码。这些行由 Id 列进行比较(您可以在 RowsComparerEquals 方法中看到它)。

namespace SO
{
    class Program
    {
        static void Main(string[] args)
        {
            var dt1 = new DataTable();
            dt1.Columns.AddRange(new[]
            {
                new DataColumn("Id", typeof(int)),
                new DataColumn("Name", typeof(string)),
                new DataColumn("Age",typeof(string))
            });

            var dt2 = new DataTable();
            dt2.Columns.AddRange(new[]
            {
                new DataColumn("Id", typeof(int)),
                new DataColumn("Name",typeof(string)),
                new DataColumn("Age",typeof(string))
            });

            dt1.Rows.Add(new object[] { 1, "Peter", "20" });
            dt1.Rows.Add(new object[] { 2, "John", "30" });

            dt2.Rows.Add(new object[] { 1, "Peter", "20" });
            dt2.Rows.Add(new object[] { 2, "John", "30" });
            dt2.Rows.Add(new object[] { 3, "Robert", "30" });

            var except = dt2.AsEnumerable().Except(dt1.AsEnumerable(), new RowsComparer());

            foreach (DataRow row in except)
                Console.WriteLine($"Id = {row[0]}, Name = {row[1]}, Age = {row[2]}");
        }

        class RowsComparer : IEqualityComparer<DataRow>
        {
            public bool Equals(DataRow x, DataRow y)
            {
                int id1 = (int)x["Id"];
                int id2 = (int)y["Id"];
                return id1 == id2;
            }

            public int GetHashCode(DataRow obj)
            {
                int hash = obj[0].GetHashCode() + obj[1].GetHashCode() + obj[2].GetHashCode();
                return hash;
            }
        }
    }

}