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

标签: c#


【解决方案1】:

你可以使用Contains():

if (myList.Contains(1))
{
}

【讨论】:

  • 明确一点,有了这个,循环就完全不需要了,可以去掉。
【解决方案2】:
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Type a number : ");
            int.TryParse(Console.ReadLine(), out int searchItem);
            List<int> items = new List<int>() { 1, 2, 3, 1 };

            //Determine if the item is in the list.
            Console.WriteLine($"{searchItem} {(items.Contains(searchItem) ? "is" : "isn't")} in the list");
            Console.WriteLine($"{searchItem} {(items.Where(item => item == searchItem).Any() ? "is" : "isn't")} in the list");
            Console.WriteLine($"{searchItem} {(items.Where(item => item == searchItem).Count() > 0 ? "is" : "isn't")} in the list");

            //Determine number of ocurrences
            Console.WriteLine($"{searchItem} is found {items.Where(item => item == searchItem).Count()} times in the list");

            Console.ReadLine();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2017-03-11
    • 2011-06-12
    • 2015-10-03
    • 2011-11-03
    相关资源
    最近更新 更多