在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方法的一些常見應用場景,它可以幫助我們在集合和字符串中快速進行元素或子字符串的檢查和判斷。