简体   繁体   中英

How to know that an object contains in a list ignoring case

I want to know how to compare an object, that if a list contains that object by ignoring case Suppose take an example for this

Class A
{
    public string p1;
    public string p2;
}

Class B
{
    List<A> lst=new List<A>();
    A obj=new a();
    A obj1=new a();

    obj1.p1="ABCD";
    obj1.p2="xyz";

    obj.p1="abcd";
    obj.p2="XYZ";
    lst.add(obj1);

    lst.contains(obj)//return false
}

So I want to know how to compare it?

You can implement IEquatable to control how your objects are compared. You can then specify exactly how you want the comparison to work by implementing the Equals() method:

 public bool Equals(A other)
 {
     return this.P1.ToLower().Equals(other.P1.ToLower());
 }

Your

lst.Contains(obj)

Should then work as you need.

In class A override the Equals method to compare each of the properties ignoring case.

Then use:

bool found = lst.FirstOrDefault(x => x.Equals(obj)) != null;
var result = lst.FirstOrDefault(c => c.p1 == obj.p1 && c.p2 == obj.p2);
if(result != null)
{
    //Your Code is here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM