

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Get the number of elements contained in Collection in C#
To get the number of elements contained in Collection, the code is as follows −
Example
using System; using System.Collections.ObjectModel; public class Demo { public static void Main() { Collection<string> col = new Collection<string>(); col.Add("Andy"); col.Add("Kevin"); col.Add("John"); col.Add("Kevin"); col.Add("Mary"); col.Add("Katie"); col.Add("Barry"); col.Add("Nathan"); col.Add("Mark"); Console.WriteLine("Count of elements = "+ col.Count); Console.WriteLine("Iterating through the collection..."); var enumerator = col.GetEnumerator(); while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } } }
Output
This will produce the following output −
Count of elements = 9 Iterating through the collection... Andy Kevin John Kevin Mary Katie Barry Nathan Mark
Example
Let us see another example −
using System; using System.Collections.ObjectModel; public class Demo { public static void Main() { Collection<int> col = new Collection<int>(); col.Add(10); col.Add(20); col.Add(30); col.Add(40); col.Add(50); col.Add(60); col.Add(70); col.Add(80); Console.WriteLine("Elements in the Collection..."); foreach(int val in col) { Console.WriteLine(val); } Console.WriteLine("Does the collection has the element 70? = "+col.Contains(70)); Console.WriteLine("Count of elements = " + col.Count); col.Clear(); Console.WriteLine("Count of elements (updated) = " + col.Count); } }
Output
This will produce the following output −
Elements in the Collection... 10 20 30 40 50 60 70 80 Does the collection has the element 70? = True Count of elements = 8 Count of elements (updated) = 0
- Related Questions & Answers
- Get the number of elements contained in SortedList in C#
- Get the number of elements contained in the Queue in C#
- Get the number of elements contained in the Stack in C#
- Get the number of elements actually contained in the ArrayList in C#
- Number of elements contained in the BitArray in C#?
- Get the number of nodes contained in LinkedList in C#
- Get the number of key/values pairs contained in OrderedDictionary in C#
- Get the number of key/value pairs contained in ListDictionary in C#
- Get the number of elements in the SortedSet in C#
- Get or set the number of elements in the BitArray in C#
- Get the count of the number of documents in a MongoDB Collection?
- Copy the elements of collection over a range of elements in ArrayList in C#
- Get a collection of keys in the StringDictionary in C#
- Get a collection of values in the StringDictionary in C#
- Get the number of elements of the Masked Array in Numpy
Advertisements