我无法在我的asp.net mvc应用程序中比较两个对象

时间:2011-09-26 18:43:44

标签: asp.net asp.net-mvc asp.net-mvc-2

我有这个代码比较两个对象,这两个输出结果是一样的。但我的平等条件总是变得虚假。我不明白我在这里做错了什么?

var t1 = repo.Model_Test_ViewAllBenefitCodes(2).OrderBy(p => p.ba_Object_id).ToArray();//.FirstOrDefault();
            var t2 = x.ViewAllBenefitCodes.OrderBy(p => p.ba_Object_id).ToArray();//.FirstOrDefault();


            for (int i = 0; i < t1.Count(); i++)
            {
                var res1 = t1[i]==(t2[i]);
                var res = t1[i].Equals(t2[i]);


                Assert.AreEqual(res, true);
            }

2 个答案:

答案 0 :(得分:2)

这实际上取决于你想要比较的对象,但这会比较只有孩子的类(没有孙子?)它使用反射来提取类中的所有属性并进行比较。

    Private Function Compare(ByVal Obj1 As Object, ByVal Obj2 As Object) As Boolean
    'We default the return value to false
    Dim ReturnValue As Boolean = False

    Try
        If Obj1.GetType() = Obj2.GetType() Then

            'Create a property info for each of our objects
            Dim PropertiesInfo1 As PropertyInfo() = Obj1.GetType().GetProperties()
            Dim PropertiesInfo2 As PropertyInfo() = Obj2.GetType().GetProperties()

            'loop through all of the properties in the first object and compare them to the second
            For Each pi As PropertyInfo In PropertiesInfo1
                Dim CheckPI As PropertyInfo
                Dim CheckPI2 As PropertyInfo
                Dim Value1 As New Object
                Dim Value2 As New Object

                'We have to do this because there are errors when iterating through lists
                CheckPI = pi
                'Here we pull out the property info matching the name of the 1st object
                CheckPI2 = (From i As PropertyInfo In PropertiesInfo2 Where i.Name = CheckPI.Name).FirstOrDefault

                'Here we get the values of the property
                Value1 = CType(CheckPI.GetValue(Obj1, Nothing), Object)
                Value2 = CType(CheckPI2.GetValue(Obj2, Nothing), Object)

                'If the objects values don't match, it return false
                If Object.Equals(Value1, Value2) = False Then
                    ReturnValue = False
                    Exit Try
                End If
            Next

            'We passed all of the checks!  Great Success!
            ReturnValue = True

        End If
    Catch ex As Exception
        HandleException(ex)
    End Try

    Return ReturnValue
End Function

答案 1 :(得分:1)

如果您可以使用自定义实体,我所做的就是覆盖Equals和GetHashCode以返回对象的标识符:

public override void Equals(object obj)
{
   if (obj == null || !(obj is MyObject))
       return false;

   return this.Key == ((MyObject)obj).Key;
}

public override int GetHashCode()
{
   return this.Key; 
   //or some other unique hash code combination, which could include
   //the type or other parameters, depending on your needs
}

这对我来说很有用,尤其是在使用LINQ的场景中,设计师生成的实体无法正确比较。我有时也会对Object.Equals(obj1, obj2)好运。