开发者

How to compare two objects excluding a single object property?

i need to avoid duplication in a list for that i used the below code . I would like to know whether there is any option to compare the objects as (item = findobject) except item.id . i dont want to type the entire property list here. Please suggest a better method.

var result =(obj.Find(item => (item== findObject)));       开发者_开发知识库     


Yes, reimplement GetHashCode(). But you need some CS knowledge to get it right, it's not trivial.

Or Equals for that matter.


Just an option: you could use reflection to get a list of properties, and then compare them bertween objects, something like:

public static bool CompareExcept<T>(T first, T second, params string[] excludeNames)
{
  foreach (PropertyInfo pi in typeof(T).GetProperties())
  {
    if (excludeNames.Contains(pi.Name)) // case sensitive
      continue;
    object propFirst = pi.GetGetMethod().Invoke(first, null);
    object propSecond = pi.GetGetMethod().Invoke(second, null);

    if (propFirst == null)
    {
      if (propSecond != null)
        return false;
    }
    else
    {
      if (!propFirst.Equals(propSecond))
        return false;
    }
  }
  return true;
}

All the usual caveats connected to reflection apply, so this is slow, and it's best avoided in tight loops, but it's relatively easy to use

Person p1 = new Person { ID = 1, FirstName = "John", LastName = "Doe", Age = 50 };
Person p2 = new Person { ID = 2, FirstName = "John", LastName = "Doe", Age = 50 };
Person p3 = new Person { ID = 3, FirstName = "Jane", LastName = "Roe", Age = 50 };
Person p4 = new Person { ID = 4, FirstName = "John", LastName = "Doe", Age = 60 };

bool areSame = CompareExcept(p1, p2, "ID"); // True
areSame = CompareExcept(p1, p2, "Age"); // False
areSame = CompareExcept(p1, p3, "ID"); // False
areSame = CompareExcept(p1, p3, "ID", "FirstName", "LastName"); // True
areSame = CompareExcept(p1, p4, "ID"); // False
areSame = CompareExcept(p1, p4, "ID", "Age"); // True

If you have lots of types you need compared, this is usefull. However, if this is a one time thing, you're better off explictly comparing all other fields.


You may override Equals method and specify list of compared properties explicitly there.


If you own the type of object to find, I suggest you to overload the Equals operator. So you will write the comparision logic once, and then will simple use "==" to compare them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜