内联比较器

时间:2015-10-18 08:08:52

标签: c# contains iequalitycomparer

我有一个具有Name属性的Person。 我有一群人。 我有一个添加新人的方法,但我需要检查已经包含该人的集合。

我想使用coll.Contains(newPerson,[here is the comparer]),比较器将在name属性上进行比较。 是否可以在不创建实现IEqualityComparer的新类的情况下进行内联(匿名)比较?

2 个答案:

答案 0 :(得分:1)

您可以改用linq。

bool contains = coll.Any(p => p.Name == newPerson.Name);

您可以根据需要在此处添加任何条件。例如,WaiHaLee指出你可以做出比较忽略的情况。

bool contains = coll.Any(p => p.Name.Equals(newPerson.Name, StringComparison.OrdinalIgnoreCase));

答案 1 :(得分:1)

如果您不想要重复的Person个对象,并希望将该集合作为一个集合进行操作,则可以使用HashSet<Person>来代替调用其Add方法如果这样的人已经存在,我会做检查。为此,您可以在班级中实施IEquatable<Person>。它看起来大致如下:

public class Person : IEquatable<Person>
{
    public Person(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }

    public bool Equals(Person other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Person) obj);
    }

    public override int GetHashCode()
    {
        return (Name != null ? Name.GetHashCode() : 0);
    }

    public static bool operator ==(Person left, Person right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(Person left, Person right)
    {
        return !Equals(left, right);
    }
}

现在你可以在你的HashSet<Person>中使用它了:

void Main()
{
    var firstPerson = new Person { Name = "Yuval" };
    var secondPerson = new Person { Name = "yuval" };
    var personSet = new HashSet<Person> { firstPerson };
    Console.WriteLine(personSet.Add(secondPerson)); // Will print false.
}

请注意,这不会为您提供多个比较器的灵活性,但这样您就不必创建实现IEqualityComparer<T>的新类。