如何使用IList.Contains()方法来找到一个对象方法来、如何使用、对象、Contains

2023-09-07 10:30:45 作者:转身ミ泪倾城

我有一个内部的公司类的人员名单。

I have a list of Persons inside a Company Class.

public class Company{
    IList<Person> persons;
}

然后,我有公司的名单,

Then I have a List of companies,

IList<Company> companies;

现在我有一个名称(例如Lasantha)。如果该名称是任何人在一个公司名称的一部分,我想找到这家公司。我试着用companies.Contains()方法。我overrided了的Object.Equals方法,Person类,因为这里面,

Now I have a name (say "Lasantha"). If this name is a part of the name of any person in a company, I want to find that company. I tried using companies.Contains() method. I overrided the object.Equals method, inside the Person class as this,

public override bool Equals(object o)
        {
            var other = o as Person;
            return this.Name.ToLower().Contains(other.Name.ToLower());
        }

不过,这是行不通的。这不是调用此方法的平等,以及。有人可以帮我请。

But this is not working. It's not calling this Equal method as well. Can someone help me please.

感谢你。

推荐答案

覆盖以这种方式相等的比较是错误的。

平等应该是传递的:如果

Equality should be transitive: if

"FooBar".Equals("Foo") == true

那么它必​​须也认为,

then it must also hold that

"Foo".Equals("FooBar") == true

然而,在这种情况下,你使用的是包含这将打破传递,因为foobar如果含有富,但富不包含FooBar的。除此之外,你不应该重写一个类,除非每一个该类的对象之间最后比较等于方法将具有相同的语义(在这种情况下似乎很可疑的)。

However, in this case you are using Contains which will break the transitivity because "FooBar" contains "Foo", but "Foo" does not contain "FooBar". Apart from that, you should not override the Equals method on a class unless each and every last comparison between objects of that class will have the same semantics (which in this case seems highly dubious).

因此​​,考虑到覆盖等于不是解决办法,有什么的应的你怎么办?

So, given that overriding Equals is not the solution, what should you do?

一种方便的方法是使用LINQ:

One convenient way is to use LINQ:

var companiesWithPeopleWithLasanthaInTheirName = 
    companies.Where(c => c.persons.Any(p => p.Name.Contains("Lasantha")));

不过上面的比较是大小写敏感的,所以如果你需要它不是你要调整它;有这个问题的答案:不区分大小写包含(字符串)