c#中contains方法怎么使用

c#
小億
82
2024-06-11 14:42:34
欄目: 編程語言

在C#中,Contains方法用于檢查集合(如數(shù)組、列表、字典等)中是否包含特定元素。下面是使用Contains方法的示例:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };

        // 使用Contains方法檢查集合中是否包含特定元素
        if (numbers.Contains(3))
        {
            Console.WriteLine("集合中包含元素3");
        }
        else
        {
            Console.WriteLine("集合中不包含元素3");
        }
    }
}

在上面的示例中,我們首先創(chuàng)建了一個(gè)包含整數(shù)的列表numbers,然后使用Contains方法檢查列表中是否包含元素3。最終輸出結(jié)果為"集合中包含元素3"。

0