首页 > 解决方案 > 如何检查数字是否是c#中列表的元素?

问题描述

在 Python 中,我可以这样做:

if 1 in [1, 2, 3, 1]:
    print("The number 1 is an element of this list.")
else:
    print("The number 1 is not an element of this list.")

我想在 c# 中做类似的事情。到目前为止,我一直在这样做:

using System;
using System.Collections.Generic;

namespace CheckMembership
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> myList = new List<int>() { 1, 2, 3, 1 };

            for (int i = 0; i < myList.Count; i++)
            {
                if (myList[i] == 1)
                {
                    Console.WriteLine("The number 1 is an element of this list.");
                    break;
                }

                if (i == myList.Count - 1 && myList[i] != 1)
                    Console.WriteLine("The number 1 is not an element of this list.");
            }
        }
    }
}

有没有更简洁有效的方法来做到这一点,也许没有循环?

标签: c#

解决方案


您可以使用Contains()

if (myList.Contains(1))
{
}

推荐阅读