Object comparison but ignore case of strings

499 Views Asked by At

I have an object like so:

public class MyObject {
    public string firstname { get; set; }
    public string lastname { get; set; }
    public int age { get; set; }
    public string occupation { get; set; }
}

I am trying to do a comparison of two objects but I want all strings to ignore case. Unfortunately the following won't compile:

// Does NOT allow me to call using ignore case
if (myObject1.Equals(myObject2, StringComparison.OrdinalIgnoreCase)) {
    Console.WriteLine("Match!");
}

Is there a way to accomplish this without manually checking each property in the object?

2

There are 2 best solutions below

0
Krzysztofz01 On

You can override the Equals() method of your class (it is a method that every object has). Everything is well described in the documentation.

public override bool Equals(Object obj)
   {
      //Check for null and compare run-time types.
      if ((obj == null) || ! this.GetType().Equals(obj.GetType()))
      {
         return false;
      }
      else {
         Point p = (Point) obj;
         return (x == p.x) && (y == p.y);
      }
   }
0
Dmitry Bychenko On

To compare equality, you can implement Equals, let's do it with a help of IEquatable<MyObject> interface:

public class MyObject : IEquatable<MyObject> {
  public string firstname { get; set; }
  public string lastname { get; set; }
  public int age { get; set; }
  public string occupation { get; set; }

  public bool Equals(MyObject other) {
    if (ReferenceEquals(this, other))
      return true;
    if (null == other)
      return false;

    return 
      string.Equals(firstname, other.firstname, StringComparison.OrdinalIgnoreCase) &&
      string.Equals(lastname, other.lastname, StringComparison.OrdinalIgnoreCase) &&
      string.Equals(occupation, other.occupation, StringComparison.OrdinalIgnoreCase) &&
      age == other.age;
  }

  public override bool Equals(object obj) => obj is MyObject other && Equals(other);

  public override int GetHashCode() =>
    (firstname?.GetHashCode(StringComparison.CurrentCultureIgnoreCase) ?? 0) ^
    (lastname?.GetHashCode(StringComparison.CurrentCultureIgnoreCase) ?? 0) ^
    (occupation?.GetHashCode(StringComparison.CurrentCultureIgnoreCase) ?? 0) ^
     age;
}

then you can use the customized Equals

if (myObject1.Equals(myObject2)) {...}