c# - 如何检查数字是否是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.");
}
}
}
}
有没有更简洁有效的方法来做到这一点,也许没有循环?
解决方案
您可以使用Contains()
:
if (myList.Contains(1))
{
}
推荐阅读
- reactjs - 类型错误:js_cookie__WEBPACK_IMPORTED_MODULE_4___default.a.getJSON 不是函数
- docker - 对容器和 Docker 层表示感到困惑
- flutter - 如何在颤动中使用挑选的图像作为背景图像?
- yarnpkg - 嵌套包的选择性解析语法
- cypress - 如何使用柏树单击具有特定内容的 div 内的按钮?
- bash - Replcae \n 使用带有新行的 sed
- firebase - 云功能的安全规则
- reactjs - 如何在firebase存储中上传图片并使用swr-firestore在react中获取上传的图片url
- python - 如何限制每几秒刷新一次的页面中python beautifulsoup中抓取的数据
- c# - 使用 IIS 服务器部署和加载 DLL