ARTICLE

StringCollection in C#

Posted by Mahesh Chand Articles | String in C# May 23, 2010
StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. In this article, we will discuss how to take advantages of its methods and properties to manage a collection of strings.
Reader Level:
Download Files:
 

StringCollection

StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. In this article, we will discuss how to take advantages of its methods and properties to manage a collection of strings.

StringCollection class defined in the System.Collections.Specialized namespace represents a collection of strings and provides functionality to manage the collection.

Creating StringCollection

The following code snippet creates an object of StringCollection class using the default constructor.

StringCollection authorNames = new StringCollection();

Adding Strings

StringCollection class provides following three methods to add strings to a string collection.

Add
AddRange
Insert

Add method is used to add string to a StringCollection at the end of the collection. The following code snippet adds strings to a StringCollection.

// Add string using Add method

authorNames.Add("Mahesh Chand");

authorNames.Add("Mike Gold");

authorNames.Add("Praveen Kumar");

authorNames.Add("Raj Beniwal");

 

AddRange method is used to add an array of strings to a StringCollection at the end of the collection. The following code snippet adds an array of strings to a StringCollection.

// Add an array of string using AddRange           

string[] names = new string[]{"Mahesh Chand", "Mike Gold", "Praveen Kumar", "Raj Beniwal"};

authorNames.AddRange(names);

 

Insert method is used to insert a string at the specified location of a StringCollection. The following code snippet inserts a string at the 5th position in a StringCollection. You will get out of bounds error message if the StringCollection does not have 5 items in it.

// Insert an string at a specified index

authorNames.Insert(5, "New Author");

Accessing Strings

The foreach loop statement in C# is used to iterate through a collection of objects such as integer or string. 

The following code snippet creates an array of strings, adds strings to a StringCollection and later uses foreach statement to loop through the collection and display on the system console.

StringCollection authorNames = new StringCollection();

string[] names = new string[]{"Mahesh Chand", "Mike Gold", "Praveen Kumar", "Raj Beniwal"};

authorNames.AddRange(names);

 

foreach (string name in authorNames)

{

    Console.WriteLine(name);

}

 

Removing Strings

StringCollection class provides following three methods to remove strings to a string collection.

Clear
Remove
RemoveAt

Clear method removes all items from a StringCollection. The following code snippet removes all items from a StringCollection.

authorNames.Clear();

 

Remove method removes the first occurrence of a given string from the string collection. The following code snippet removes a string from a StringCollection.

authorNames.Remove("Mike Gold");

 

RemoveAt method removes a string specified at the given location from the string collection. The following code snippet removes a string at the specified index from a StringCollection.

authorNames.RemoveAt(5);

Find String

IndexOf method searches for the specified string and returns the zero-based index of the first occurrence within the StringCollection. The following code snippet finds the position of a string in a string collection.

int authorLocation = authorNames.IndexOf("Mike Gold");

Console.WriteLine("Position of Mike Gold is " + authorLocation.ToString());

 

Contains method returns true if a string is found in a StringCollection. The following code snippet checks if a string is found in the collection and returns the position in a string collection.

if (authorNames.Contains("Mike Gold"))

{

    Console.WriteLine("Mike Gold is at position: " + authorNames.IndexOf("Mike Gold"));

}

Copy Strings

CopyTo method of StringCollection is used to copy items from a StringCollection to an array. The CopyTo method takes two arguments. First is the name of the StringCollection and second is the starting position in the StringCollection. The following code snippet copies all items from authorNames StringCollection to an array.

// Copy Collection to new Array

string[] newAuthorList = new string[authorNames.Count];

authorNames.CopyTo(newAuthorList, 0);

 

foreach (string name in newAuthorList)

{

    Console.WriteLine(name);

}

 

Count Strings

Count property returns total number of items in in a StringCollection. The following code snippet returns number of items in authorNames collection.

Console.WriteLine("Total items in string collection: " + authorNames.Count.ToString());

 

Getting Items

ArrayCollection is a collection. That means, you can access its items by using an index. The following code snippet looks for the position of a string and accesses it using Item property.

int authorLocation = authorNames.IndexOf("Mike Gold");

string authorName = authorNames[authorLocation];

 

Complete Code

Here is the listing of complete code we have discussed in this article.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

using System.Collections.Specialized;

 

 

namespace StringCollectionSample

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create a StringCollection object

            StringCollection authorNames = new StringCollection();

 

            // Add string using Add method

            authorNames.Add("Mahesh Chand");

            authorNames.Add("Mike Gold");

            authorNames.Add("Praveen Kumar");

            authorNames.Add("Raj Beniwal");

 

            // Add an array of string using AddRange           

            string[] names = new string[]{"Mahesh Chand", "Mike Gold", "Praveen Kumar", "Raj Beniwal"};

            authorNames.AddRange(names);

 

            // Insert an string at a specified index

            authorNames.Insert(5, "New Author");

 

            // authorNames.Clear();

            // authorNames.Remove("Mike Gold");

            // authorNames.RemoveAt(5);

 

            if (authorNames.Contains("Mike Gold"))

            {

                Console.WriteLine("Mike Gold is at position: " + authorNames.IndexOf("Mike Gold"));

            }

 

            int authorLocation = authorNames.IndexOf("Mike Gold");

            string authorName = authorNames[authorLocation];

 

            Console.WriteLine("Position of Mike Gold is " + authorLocation.ToString());

 

            Console.WriteLine("Total items in string collection: " + authorNames.Count.ToString());

 

            foreach (string name in authorNames)

            {

                Console.WriteLine(name);

            }

 

            // Copy Collection to new Array

            string[] newAuthorList = new string[authorNames.Count];

            authorNames.CopyTo(newAuthorList, 0);

 

            foreach (string name in newAuthorList)

            {

                Console.WriteLine(name);

            }

            //int[] intArray = new int[] { 0, 1, 2, 3, 5, 8, 13 };

            //foreach (int i in intArray)

            //{

            //    System.Console.WriteLine(i);

            //}

 

            Console.ReadLine();

 

 

        }

    }

}

 

Summary

StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. In this article, we saw how to take advantages of this class and its methods and properties to manage a collection of strings.

Login to add your contents and source code to this article
post comment
     

i like it :)

Posted by Lajapathy Arun Sep 18, 2012

Thank you for your article,I'm new in C# programming,and after learning your article,I've understood how to use StringSelection.

Posted by Wang Zhan Mar 07, 2012

thats great article
Asif Iqbal
Software Eng

Posted by Asif Iqbal Jun 19, 2010

it's impelemted by ArrayList,and it's Not New actually!

Posted by gaoren li May 25, 2010

Developers have been asking Microsoft for this class for a while.

You can use same thing using List<String> but if some body does not know generics, will have hard time to understand it.

Posted by Mahesh Chand May 24, 2010
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter