Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check whether a List contains a specified element in C#
To check whether a List contains a specified element, the code is as follows −
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
List<string> list1 = new List<string>();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
list1.Add("Five");
Console.WriteLine("Elements in List1...");
foreach (string res in list1){
Console.WriteLine(res);
}
List<string> list2 = new List<string>();
list2.Add("India");
list2.Add("US");
list2.Add("UK");
list2.Add("Canada");
list2.Add("Poland");
list2.Add("Netherlands");
Console.WriteLine("Elements in List2...");
List<string>.Enumerator demoEnum = list2.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("Is List2 equal to List1? = "+list2.Equals(list1));
Console.Write("Does List2 has element Canada? = "+list2.Contains("Canada"));
}
}
Output
This will produce the following output −
Elements in List1... One Two Three Four Five Elements in List2... India US UK Canada Poland Netherlands Is List2 equal to List1? = False Does List2 has element Canada? = True
Example
Let us now see another example −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
list.Add(500);
list.Add(600);
list.Add(700);
list.Add(800);
list.Add(900);
list.Add(1000);
Console.WriteLine("Elements in List...");
foreach (int res in list){
Console.WriteLine(res);
}
Console.Write("Does List has element 150? = "+list.Contains(150));
}
}
Output
This will produce the following output −
Elements in List... 100 200 300 400 500 600 700 800 900 1000 Does List has element 150? = False
Advertisements