C# 如何判断列表是否不包含元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17381332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:22:49  来源:igfitidea点击:

How to tell if a list does not contain an element?

c#

提问by user2534753

I am trying to make a small program in which checks to see if the box is checked and if it is it will add an element to the list "names". But I need it to check if the name isn't already in the list before it adds the element.

我正在尝试制作一个小程序,在其中检查该框是否已选中,如果已选中,它将向列表“名称”添加一个元素。但是我需要它在添加元素之前检查名称是否已经在列表中。

采纳答案by James

The Containsmethod

包含方法

if (!myList.Contains("name"))
{
    myList.Add("name");
}

Or Anymethod

任何方法

if (!myList.Any(s => s == "name"))
{
    myList.Add("name");
}

would do the job. You don't specify whether the check is case sensitive or not, these checks are both case sensitivebut it's easy enough to update for case insensitive checks.

会做的工作。您没有指定检查是否区分大小写,这些检查都是区分大小写的,但是很容易更新不区分大小写的检查。

回答by keyboardP

You can use a HashSetinstead, it's designed to not allow any duplicates.

您可以改用HashSet,它的设计不允许任何重复项。