简体   繁体   中英

C# check whether value is present in the List<> or not

检查该值是否存在于List然后在c#中插入该值的有效方法是什么?

You can use Contains method to check whether value is in the list:

if(!valuesList.Contains(value)) 
{
  valuesList.Add(value);
}

Use Contains and Add :

if (!myList.Contains(myValue)) {
    myList.Add(myValue);
}

You're looking for Contains() and Add() , quick example:

if (!theList.Contains(theValue))
{
    theList.Add(theValue);
}

use method bool List.Contains(T) for check, and void List.Add(T) for addition

or create extension:

public static void AddIfNotExist<T>(this List<T> list, T item)
{
    if (list.Contain(item))
    {
        list.Add(item);
    }
}

using list.AddIfNotExist(item)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM