.NET List Class

The .NET List Class represents a strongly typed list of objects. It also provides methods to search, sort, and manipulate lists.

The following code gives an example on how the List Class can be used.

#Initialize a new instance of the List<T> class that is empty
#and has the specified initial capacity of 10. The type of
#elements in the list will be strings.
$mylist = New-Object -TypeName System.Collections.Generic.List[System.String](10);

#Create a string containing some words for us to play with.
$fox="the quick brown fox jumps over the lazy dog";

#Split the words up and place them into an array.
$words=$fox.Split(' ');

#Show the capacity of the list object.
Write-Host "mylist has capacity $($mylist.Capacity)";

#Clear the object just before we use it.
$mylist.Clear();

#Loop through the array and place the words into the 'List' object.
foreach ($w in $words) {
    $mylist.Add($w);
}

#Show how many items we have in the 'List' object.
Write-Host "mylist has $($mylist.Count) items";

#See if we can find a fox in the list.
$searchWord="fox";
if ($mylist.Contains($searchWord)) {
   Write-Host "We have a $($searchWord) in the list";
} else {
   Write-Host "The $($searchWord) isn't around";
}

#List the words as entered into the list.
Write-Host "`nUnsorted list output";
$num=0;
$mylist.GetEnumerator() | Foreach-Object {
    Write-Host ("Word number {0} = {1}" -f ++$num, $_);
}

#Produce a sorted list of words.
Write-Host "`nSorted list output";
$num=0;
$mylist.GetEnumerator() | Sort-Object | Foreach-Object {
    Write-Host ("Word number {0} = {1}" -f ++$num, $_);
}

Lines 41-46 produced a sorted output to the console. The contents of mylist are not really sorted as we used the Sort-Object cmdlet to display the contents in a sorted order. If you really want to sort the contents of your list, then Sort() method can be used. i.e.


$mylist.Sort();

Advertisements
This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s