如何使用IList.Contains()方法来找到一个对象 [英] How to use IList.Contains() method to find an object

查看:342
本文介绍了如何使用IList.Contains()方法来找到一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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")));

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

这篇关于如何使用IList.Contains()方法来找到一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆