C# | How to check whether a List contains a specified element - GeeksforGeeks (2024)

Last Updated : 20 Jun, 2022

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

List<T>.Contains(T) Method is used to check whether an element is in the List<T> or not. Properties of List:

  • It is different from the arrays. A list can be resized dynamically but arrays cannot.
  • List class can accept null as a valid value for reference types and it also allows duplicate elements.
  • If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.

Syntax:

public bool Contains (T item);

Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False. Below programs illustrate the use of List<T>.Contains(T) Method: Example 1:

CSharp

// C# Program to check whether the

// element is present in the List

// or not

using System;

using System.Collections;

using System.Collections.Generic;

class Geeks {

// Main Method

public static void Main(String[] args)

{

// Creating an List<T> of Integers

List<int> firstlist = new List<int>();

// Adding elements to List

firstlist.Add(1);

firstlist.Add(2);

firstlist.Add(3);

firstlist.Add(4);

firstlist.Add(5);

firstlist.Add(6);

firstlist.Add(7);

// Checking whether 4 is present

// in List or not

Console.Write(firstlist.Contains(4));

}

}

Output:

True

Example 2:

CSharp

// C# Program to check whether the

// element is present in the List

// or not

using System;

using System.Collections;

using System.Collections.Generic;

class Geeks {

// Main Method

public static void Main(String[] args)

{

// Creating an List<T> of String

List<String> firstlist = new List<String>();

// Adding elements to List

firstlist.Add("Geeks");

firstlist.Add("For");

firstlist.Add("Geeks");

firstlist.Add("GFG");

firstlist.Add("C#");

firstlist.Add("Tutorials");

firstlist.Add("GeeksforGeeks");

// Checking whether Java is present

// in List or not

Console.Write(firstlist.Contains("Java"));

}

}

Output:

False

Time complexity: O(n) for Contains method

Auxiliary Space: O(n) where n is size of the list

Reference:



K

Kirti_Mangal

C# | How to check whether a List contains a specified element - GeeksforGeeks (2)

Improve

Next Article

C# | Check if a HashSet contains the specified element

Please Login to comment...

Similar Reads

C# | How to check whether a List contains the elements that match the specified conditions List<T>.Exists(Predicate<T>) Method is used to check whether the List<T> contains elements which match the conditions defined by the specified predicate. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot.List class can accept null as a valid value for reference types and it al 3 min read C# | Check if a HashSet contains the specified element A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.Contains(T) Method is used to check whether a HashS 2 min read C# | Check if SortedDictionary contains the specified key or not SortedDictionary<TKey, TValue>.ContainsKey(TKey) Method is used to check whether the SortedDictionary contains an element with the specified key or not. Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the SortedDictionary. Returns Value: This method will return true if the Dictionary contains an 2 min read C# | Check whether a Hashtable contains a specific key or not Hashtable.Contains(Object) Method is used to check whether the Hashtable contains a specific key or not. Syntax: public virtual bool Contains (object key); Here, key is the Key of Object type which is to be located in the Hashtable. Return Value: This method returns true if the Hashtable contains an element with the specified key otherwise returns 2 min read C# | Check whether a SortedList object contains a specific key SortedList.Contains(Object) Method is used to check whether a SortedList object contains a specific key. Syntax: public virtual bool Contains (object key); Here, key is the Key which is to be located in the SortedList object. Return Value: This method returns the true if the SortedList object contains an element with the specified key otherwise, it 2 min read C# | Removing the specified element from the List List.Remove(T) Method is used to remove the first occurrence of a specific object from the List. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then 2 min read C# | Gets or Sets the element at the specified index in the List List<T>.Item[Int32] Property is used to gets or sets the element at the specified index. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then t 2 min read C# | How to remove the element from the specified index of the List List<T>.RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals 3 min read C# | How to get the last occurrence of the element in the List that match the specified conditions List<T>.FindLast(Predicate<T>) Method is used to search for an element which matches the conditions defined by the specified predicate and it returns the last occurrence of that element within the entire List<T>. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot.List class can 4 min read C# | How to perform a specified action on each element of the List List<T>.ForEach(Action<T>) Method is used to perform a specified action on each element of the List<T>. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count become 2 min read C# | Check if a Stack contains an element Stack represents a last-in, first out collection of object. Stack<T>.Contains(Object) Method is used to check whether an element is in the Stack<T> or not. Syntax: public virtual bool Contains(object obj); Return Value: The function returns True if the element exists in the Stack<T> and returns False if the element doesn't exist i 2 min read C# | Check if the SortedSet contains a specific element SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Contains(T) Method is used to check if a SortedSet contains a specific element or not. Properties: In C#, SortedSet class can be used to store, remove or view elements. It maintains ascending order a 2 min read C# | Insert an element into the ArrayList at the specified index ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Insert(Int32, Object) method inserts an element into the ArrayList at the specified index. Properties of ArrayList 3 min read C# | Remove the element with the specified key from the Hashtable The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Remove(Object) Method is used to remove the element with the specified key from the Hashtable. Syntax: public virtual void Remove (object key); Parameter: key: It i 2 min read C# | Remove the specified element from a HashSet A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet<T>.Remove(T) method is used to remove the spe 3 min read C# | Remove the element at the specified index of the ArrayList ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveAt(Int32) method is used to remove the element at the specified index of the ArrayList. Properties: Elements 3 min read C# | Remove the element with the specified key from a SortedList SortedList class is a collection of (key, value) pairs which are sorted according to keys. Those pairs can be accessible by key and as well as by index(zero-based indexing). This comes under System.Collections namespace. SortedList.Remove(Object) method is used to remove the element with the specified key from a SortedList object. Properties: A Sor 3 min read C# | Insert an element into Collection<T> at specified index Collection<T>.Insert(Int32, T) method is used to insert an element into the Collection<T> at the specified index. Syntax: public void Insert (int index, T item); Parameters: index : The zero-based index at which item should be inserted. item : The object to insert. The value can be null for reference types. Exception: This method will g 3 min read C# | Remove element at specified index of Collection<T> Collection<T>.RemoveAt(Int32) is used to remove the element at the specified index of the Collection<T>. Syntax: public void RemoveAt (int index); Here, index is the zero-based index of the element to remove. Exception: This method will give ArgumentOutOfRangeException if the index is less than zero OR index is equal to or greater than 2 min read C# | Get or set the element at specified index in Collection<T> Collection<T>.Item[Int32] property is used to get or set the element at the specified index. Syntax: public T this[int index] { get; set; } Here, index is the zero-based index of the element to get or set. Return Value: The element at the specified index. Exception: This method will give ArgumentOutOfRangeException if the index is less than z 3 min read C# | Performing Specified action on each element of Array Array.ForEach(T[], Action<T>) Method is used to perform the specified action on each element of the specified array. Syntax: public static void ForEach<T> (T[] array, Action<T> action); Parameters: array: The one-dimensional, zero-based Array on whose elements the action is to be performed. action: The Action to perform on each el 3 min read C# | Get or set the element at the specified index in ArrayList ArrayList.Item[Int32] Property is used to get or set the element at the specified index in ArrayList. Syntax: public virtual object this[int index] { get; set; } Here, index is the zero-based index of the element to get or set. Return Value: It returns the element of Object type at the specified index. Exception: This property will throw ArgumentOu 2 min read C# | Gets or sets the element at the specified index in StringCollection StringCollection.Item[Int32] Property is used to get or set the element at the specified index. Syntax: public string this[int index] { get; set; } Here, index is the zero-based index of the entry to get or set. Return Value: It returns the element of String type at the specified index. Exception: This property throws ArgumentOutOfRangeException if 2 min read Finding the Index of First Element of the Specified Sequence in C# The Index Structure is introduced in C# 8.0. It represents a type that can be used to index a collection or sequence and it can be started from the start or the end. You are allowed to find the index, which points the first element of the specified collection or sequence with the help of Start Property provided by the Index struct. Syntax: public s 2 min read C# | Check if the specified string is in the StringCollection StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace. StringCollection.Contains(String) method is used to check whether the specified string is in the StringCollection or not. Syntax: public bool Contain 2 min read C# | Check if SortedSet and a specified collection share common elements SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet.Overlaps(IEnumerable) Method is used to check whether a SortedSet and a specified collection share common elements or not. Properties: In C#, SortedSet class can be used to store, remove or view elements. 2 min read C# | Check if HashSet and the specified collection contain the same elements Here's an example code that demonstrates how to use the Overlaps method to check if a HashSet and a specified collection share common elements in C#: C/C++ Code using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // Create a HashSet and a List HashSet<int> set1 = new HashSet<int> { 1, 2, 3, 3 min read C# | Check if a HashSet is a proper superset of the specified collection A HashSet is an unordered collection of the unique elements. It comes under the System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.IsProperSupersetOf(IEnumerable) Method is used 2 min read C# | Check if a HashSet and a specified collection share common elements In C#, you can use the SetEquals method to check if a HashSet and a specified collection contain the same elements. The SetEquals method returns true if the HashSet and the specified collection contain the same elements; otherwise, it returns false. Here is an example code that demonstrates how to use the SetEquals method to check if a HashSet and 3 min read C# | Check if a HashSet is a subset of the specified collection A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.IsSubsetOf(IEnumerable) Method is used to check whe 2 min read

Article Tags :

  • C#
  • CSharp-Collections-Namespace
  • CSharp-Generic-List
  • CSharp-Generic-Namespace
C# | How to check whether a List contains a specified element - GeeksforGeeks (2024)

FAQs

C# | How to check whether a List contains a specified element - GeeksforGeeks? ›

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How to find a specific element in a list C#? ›

Other Methods
  1. Using Enumerable.Contains() Method (System.Linq) This method helps to understand whether a specific element is present or not in a simple and easy-to-understand manner. ...
  2. Using List. IndexOf() Method. ...
  3. Using List. FindIndex() Method. ...
  4. Using List. FindAll() Method. ...
  5. Using Enumerable. ...
  6. Perform a Linear Search.
Jul 23, 2024

How do you check if a list contains a specific element? ›

Using the 'count()' Method

The 'count()' method allows you to count the occurrences of an element in a Python list. By checking if the count is greater than zero, you can determine if the element exists in the given list.

How to check if a value exists in a list in C#? ›

Syntax. public bool Contains (T value); It takes the T value as input, to be searched in the linked list. It returns true if the value is present in the linked list and false otherwise.

How to check if an array contains a specific value in C#? ›

A- You can check if an array contains a specific element in C# by using the Contains() method provided by the System. Linq namespace.

How to check if a list contains an element in C#? ›

public bool Contains (T item); Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False.

How do I access specific elements in a list? ›

The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string. We use the index operator ( [] – not to be confused with an empty list). The expression inside the brackets specifies the index. Remember that the indices start at 0.

How to get specific value from list in C#? ›

You can use Index to fetch a particular value based on the index from end. Use the caret notation, ^ to index from end. In the following example, you use Index to get the last element in the list. var myList = new List<int>{0, 1, 2}; var lastElement = myList[^1];

How do you check if an array contains a certain element? ›

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

How do you check if a string contains an element from a list? ›

One approach to check if a string contains an element from a list is to convert the string and the list into sets and then check for the intersection between the sets. If the intersection is not an empty set, it means that the string contains an element from the list.

How to check if something contains something in C#? ›

Basic Syntax for Contains() Method

Contains(CheckString); The function returns true if CheckString is found within YourString , and false if it is not. As simple as that!

How do you check if a value exists in a list of list in Python? ›

Check if an element exists in a list in Python
  • Using “in” Statement.
  • Using a loop.
  • Using any() function.
  • Using count() function.
  • Using sort with bisect_left and set()
  • Using find() method.
  • Using Counter() function.
  • Using try-except block.
Jul 8, 2024

How do you check if a value exists in a list of values in Excel? ›

Type “=IF(COUNTIF” and press Tab. 4. Then you press enter. This function will return whether a value exists in a list in simple yes or no terms instead of exact number of time as shown section 1.1.

How to get specific value from array in C#? ›

GetValue(Int32, Int32, Int32) method is used to get the value at the specified position in the three-dimensional Array. The indexes are specified as 32-bit integers. Syntax: public object GetValue (int index1, int index2, int index3);

How do you search for a specific value in an array? ›

Array.prototype.find()
  1. If you need the index of the found element in the array, use findIndex() .
  2. If you need to find the index of a value, use indexOf() . ...
  3. If you need to find if a value exists in an array, use includes() . ...
  4. If you need to find if any element satisfies the provided testing function, use some() .
Feb 5, 2024

How do you check if an array of objects contains a specific key? ›

How can I check if a key exists in a JavaScript object or array? You can use the in-operator or the hasOwnProperty() method to check if a key is in a JavaScript object or array. The in operator tells you if the key is there, and the hasOwnProperty() method shows if the key is a direct property of the object.

How to find distinct elements in a list in C#? ›

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).

How to find the same element in a list C#? ›

👉 Using HashSet :

HashSet is a data structure, that holds the unique items. Using HashSet , we can easily find the duplicates in array. This approach involves iterating over the input array and adding each element to a HashSet. If an element is already present in the HashSet, it is considered a duplicate.

How to get particular index value in list in C#? ›

To get the index of an item in a single line, use the FindIndex() and Contains() methods. int index = myList. FindIndex(a => a.

Top Articles
What are the Advantages and Disadvantages of Trading in a Car? Ithaca NY | Maguire Volkswagen
Average Cost of Petrol for a Car 2024
Nambe Flatware Discontinued
Danielle Ranslow Obituary
Kia North Huntingdon Pa
J'ai essayé cette astuce Abercrombie & Fitch qui est partout sur Internet.
Bridgeport Transit Bus Schedule
Harbin Clinic Immediate Care
Log in or sign up to view
Sunset Intimates Argyle
Katinakay Leaks
Vistaprint Search Engine Listings Manager Review
Cbs Straight Up Picks
Anime Fruit Simulator Trello
What Does Recharge Mean In Mcgraw Hill Connect
How Multiplayer Matchmaking Works in Elden Ring
Larue County Pva
27L1576
Citymd West 146Th Urgent Care - Nyc Photos
Call2Recycle Sites At The Home Depot
Rugged Gentleman Barber Shop Martinsburg Wv
Marcus Roberts 1040 Answers
Steelweb Usw
Standard Bank Learnership Programme 2021
Tuscora Park in New Philadelphia | Ohio - on FamilyDaysOut.com
What Happened To Guy Yovan's Voice
Robert Mkalech
Plaza Bonita Sycuan Bus Schedule
norfolk gigs - craigslist
Sunday Td Bank
Directions To 401 East Chestnut Street Louisville Kentucky
Ang420S
21 Alive Weather Team
K Pocha - Korean Pub Aurora Reviews
Quest Diagnostics Mt Morris Appointment
TamilMV Proxy List (Jan 2024) 1TamilMV Mirrors To Unblock
Austin’s Craigslist: Your Ultimate Guide to Buying, Selling, and Discovering
Kenton County Busted Mugshots
Accuweather Mold Count
Shauna's Art Studio Laurel Mississippi
Meijer Former Employee W2
Wnjn Tv Schedule
Myrtle Lowater Obituary 2021 - Pederson-Volker Funeral Chapel & Cremation Services
Wright Donaldson Obituaries
Mccommons Funeral Home Obituaries
Goanimate Gina Delgado
Stranded Alien Dawn Cave Dweller
Yagurlbubbz
Restored Republic Jan 3 2023
Craigslist Domestic Job
Combat Rogue Bis Phase 2
Qvc Host Dies Lisa Robertson Cause Of Death
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated:

Views: 6533

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.