在C#中,Contains方法通常用于判断集合或字符串是否包含指定的元素或子字符串。以下是Contains方法的一些常见应用场景:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
if (numbers.Contains(3))
{
Console.WriteLine("List contains 3");
}
string sentence = "Hello, world!";
if (sentence.Contains("world"))
{
Console.WriteLine("Sentence contains 'world'");
}
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
if (numbers.Contains(x => x > 3))
{
Console.WriteLine("List contains element greater than 3");
}
public class Person
{
public string Name { get; set; }
public override bool Equals(object obj)
{
return obj is Person other && Name == other.Name;
}
}
List<Person> people = new List<Person>
{
new Person { Name = "Alice" },
new Person { Name = "Bob" }
};
Person person = new Person { Name = "Alice" };
if (people.Contains(person))
{
Console.WriteLine("List contains person with name 'Alice'");
}
这些是Contains方法的一些常见应用场景,它可以帮助我们在集合和字符串中快速进行元素或子字符串的检查和判断。