Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# IEnumerable<;伊达塔雷科德>;比较_C#_Linq - Fatal编程技术网

C# IEnumerable<;伊达塔雷科德>;比较

C# IEnumerable<;伊达塔雷科德>;比较,c#,linq,C#,Linq,我有以下方法: public static IEnumerable<IDataRecord> DbQueryToArray(string connectionString, string sql) { if (null == sql) throw new ArgumentNullException(nameof(sql)); string SqlCString = connectionString;

我有以下方法:

public static IEnumerable<IDataRecord> DbQueryToArray(string connectionString, string sql)
    {
        if (null == sql)
            throw new ArgumentNullException(nameof(sql));

        string SqlCString = connectionString;

        using (SqlConnection connection = new SqlConnection(SqlCString))
        {
            connection.Open();
            if (connection == null)
                throw new Exception("Db's down.");

            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        yield return reader as IDataRecord;
                    }
                }
            }
            if (connection != null)
                connection.Close();
        }
    }
输出两个阵列之间的差值/秒的最有效和最简单的方法是什么


谢谢

首先我们需要一种比较记录的方法

public class DataRecordComparer : IEqualityComparer<IDataRecord>
{
    public bool Equals(IDataRecord x, IDataRecord y)
    {
        var a = new object[x.FieldCount];
        var b = new object[y.FieldCount];

        x.GetValues(a);
        y.GetValues(b);

        return a.SequenceEqual(b);
    }

    public int GetHashCode(IDataRecord obj)
    {
        var values = new object[obj.FieldCount];
        obj.GetValues(values);

        unchecked
        {
            int hash = 17;
            foreach (var item in values.Where(x => x != null))
                hash = hash * 23 + item.GetHashCode();

            return hash;
        }
    }
}
出于性能方面的原因,您可能希望在数据库中执行此操作,并且只返回差异。您可以使用类似的方法,只是不需要比较器

select a,b,c
from tbl1

except

select a,b,c
from tbl2

union all

select a,b,c
from tbl2

except

select a,b,c
from tbl1

(我没有时间测试代码,所以可能会有一些问题,但至少它应该为您指明了正确的方向。)

为什么不将这项工作委托给数据库,形成一个查询,让您了解差异?谢谢nvoigt。如果表驻留在两个不同的数据库上,可以这样做吗?
var comparer = new DataRecordComparer();
var diff = table_1.Except(table_2, comparer).Concat(table_2.Except(table_1, comparer));
select a,b,c
from tbl1

except

select a,b,c
from tbl2

union all

select a,b,c
from tbl2

except

select a,b,c
from tbl1