📜  C#|检查值是否在LinkedList中<T>

📅  最后修改于: 2021-05-29 21:23:08             🧑  作者: Mango

LinkedList < T > .Contains(T)方法用于检查值是否在LinkedList 中。

句法:

public bool Contains (T value);

在此,是要在LinkedList < T >中定位的值。对于引用类型,该值可以为null。

返回值:如果在LinkedList中找到值,则此方法返回True ,否则返回False

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to check if a
// value is in LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Strings
        LinkedList myList = new LinkedList();
  
        // Adding nodes in LinkedList
        myList.AddLast("A");
        myList.AddLast("B");
        myList.AddLast("C");
        myList.AddLast("D");
        myList.AddLast("E");
  
        // To check if a value is in LinkedList
        Console.WriteLine(myList.Contains("B"));
    }
}

输出:

True

范例2:

// C# code to check if a
// value is in LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Integers
        LinkedList myList = new LinkedList();
  
        // Adding nodes in LinkedList
        myList.AddLast(1);
        myList.AddLast(2);
        myList.AddLast(3);
        myList.AddLast(4);
        myList.AddLast(5);
  
        // To check if a value is in LinkedList
        Console.WriteLine(myList.Contains(8));
    }
}

输出:

False

注意:此方法执行线性搜索。因此,此方法是O(n)运算,其中n是Count。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.linkedlist-1.contains?view=netframework-4.7.2