C# Contains Method Guide

In C#, the Contains method is used to check if a collection or string contains a specific element or sub-string. It returns a boolean value indicating whether the specified element or sub-string exists in the collection or string.

Here is an example of how to use the Contains method:

  1. Includes
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
bool containsNumber = numbers.Contains(3);
Console.WriteLine(containsNumber); // 输出: True
  1. Includes
string text = "Hello World";
bool containsSubstring = text.Contains("World");
Console.WriteLine(containsSubstring); // 输出: True
  1. Includes
class Person
{
    public string Name { get; set; }
}

List<Person> people = new List<Person>
{
    new Person { Name = "John" },
    new Person { Name = "Jane" },
    new Person { Name = "Bob" }
};

Person person = new Person { Name = "Jane" };
bool containsPerson = people.Contains(person, new PersonEqualityComparer());
Console.WriteLine(containsPerson); // 输出: True

// 自定义比较器
class PersonEqualityComparer : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        return x.Name.Equals(y.Name);
    }

    public int GetHashCode(Person obj)
    {
        return obj.Name.GetHashCode();
    }
}

In the above example, the Contains method is used to check if a specific element exists in a collection or if a specific sub-string exists in a string. For custom class collections, you can specify how to compare objects by implementing the IEqualityComparer interface.

bannerAds