Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two Linq objects

Tags:

c#

.net

linq

I wanna compare two identical Linq table objects iterating through theirs properties but I have to omit some properties, which are generic type with one parameter e.g. EntitySet (LinqTable has many different types), how could I check if property is that type (EntitySet)?

Sorry for no code, but I write from mobile phone :) I will append some code if it will be necessary ;)

EDIT:

I finally solve that problem with code below:

internal static void AssertIsEqualTo<T>(this T value, T comparedValue, List<string> fieldsToAvoid)
{
    Type type = typeof(T);
    PropertyInfo[] properties = type.GetProperties();

    if (fieldsToAvoid == null)
    {
        fieldsToAvoid = new List<string>();
    }

    for (int i = 0; i < properties.Length; i++)
    {
        var expectedPropertyValue = properties[i].GetValue(value, null);
        var actualPropertyValue = properties[i].GetValue(comparedValue, null);

        if (!fieldsToAvoid.Contains(properties[i].Name))
        {
            if (properties[i].PropertyType.Name != typeof(System.Data.Linq.EntitySet<object>).Name)
            {
                Assert.AreEqual(expectedPropertyValue, actualPropertyValue, "In {0} object {1} is not equal.", type.ToString(), properties[i].Name);
            }
        }
    }
}

In Name Property of Type object is something like "EntitySet '1" which means EntitySet object with one parameter.

Maybe someone knows better way to solve that?

like image 896
mrzepa Avatar asked Dec 21 '25 05:12

mrzepa


1 Answers

Create a class that implements IEqualityComparer e.g.

public class ProjectComparer : IEqualityComparer<Project>
{
    public bool Equals(Project x, Project y)
    {
        if (x == null || y == null)
            return false;
        else
            return (x.ProjectID == y.ProjectID);
    }

    public int GetHashCode(Project obj)
    {
        return obj.ProjectID.GetHashCode();
    }
}

Replace the logic in the Equals method with whatever you need, then use to compare your objects in one of various ways e.g. most simply:

bool areEqual = new ProjectComparer().Equals(project1, project2);
like image 137
Tom Troughton Avatar answered Dec 23 '25 21:12

Tom Troughton