【发布时间】:2020-02-27 21:59:01
【问题描述】:
在 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.");
}
}
}
}
有没有更简洁有效的方法来做到这一点,也许没有循环?
【问题讨论】:
-
您的循环解决方案是一个好的开始,但它可能需要一些工作。你能用
static bool Contains(List<int> items, int candidate) { ... }这个签名写一个方法,如果候选人在列表中,则返回true,否则返回false?如果你能这样做,那么你可以让你的Main方法更容易阅读;if(Contains(myList, 1)) ...作为一个初学者,总是问自己“我能把这个功能提取到一个能很好地解决一个问题的方法中吗?”这就是我们制作用于解决更大问题的方法库的方式。 -
现在,正如答案指出的那样,有人已经为您编写了该方法。但是通过自己编写“基本”方法作为学习练习,您会发现编写这些库方法并不神奇;它们是由开发人员编写的,您可能是其中之一。
-
另外我注意到您的解决方案不太正确。例如,如果您的列表是empty,会发生什么?它应该产生
1 is not an element的消息,因为列表是空的。但是你的程序没有这样做。你知道如何解决这个问题吗? -
谢谢你,埃里克。事实上,我是一个初学者,只是把编码作为一种爱好,所以我发现你的指导方针非常有帮助。我确实喜欢编写自己的方法作为学习工具,然后我会寻找现有的方法来使我的代码看起来更好,工作得更好。
标签: c#