Introduction to Collections
Introduction to Collections
Fundamentals of Collections
Introduction
A collection, also called a list, is a group of items. Normally, the items should be of the same type. The collection can be made of numbers, or symbols, or dates, or strings, etc. The collection can also be made of objects (of a class), such as houses, people, cars, countries, etc. The primary rule to observe is that all items included in a list must be described using the same characteristics.
Starting a Collection
To start a collection, create a class. This class would be used to add items in the collection, to remove items from the list, or to perform other necessary operations. You can start a simple class as follows:
public class Collection { }
Since this is a normal class, you can add various types of members to it, including properties, methods, etc. Here is an example of a class with a constructor:
public class State
{
public Collection()
{
}
}
After creating the class for a collection, the collection becomes an object and its class can be used like any other. This means that, before using the collection, you can declare a variable for it. Here are examples of such variables:
public class StatesStatistics
{
public static void Main(string[] args)
{
Collection states = new Collection();
var estados = new Collection();
dynamic pays = new Collection();
}
}
As we saw in previous lessons, an array is one type of list you can create. In fact, to create a collection, you can start by adding a field array as one of its members. Here is an example:
public class Collection { // This is an array that will hold the items of this collection private string[] items; public Collection() { // Start the list with 0 item. items = new string[0]; } }
There are many other ways you can start an array.
The Number of Items in a Collection
It is important to know the number of items in a collection at any item. If you create a collection that is array-based, because you must specify the number of items that the array will contain, you would need to specify a number of items. To keep track of the number of items in the collection, you create a private field and initialize it to 0 in the constructor to indicate its primary number of items. Here is an example:
public class Collection { // This is the size of the collection private int size; // This is an array that will hold the items of this collection private string[] items; // This constructor will be used to initialize the list public Collection() { // When the list starts, it is empty: it's size is 0 size = 0; // Start the list with 0 item. items = new string[0]; } }
Since the size field was declared private, if you plan to get the count of items in the list from outside the class, you should (must) provide a property to take care of this. This can simply be done as follows:
public class Collection
{
// This is the size of the collection
private int size;
private string[] items;
public Collection()
{
size = 0;
items = new string[10];
}
// This represents the number of items in the collection
public int Count
{
get { return size; }
}
}
Here is an example of accessing the number of items in the collection:
using static System.Console; public class Collection { // This is the size of the collection private int size; private string[] items; public Collection() { size = 0; items = new string[10]; } // This represents the number of items in the collection public int Count { get { return size; } } } public class MetropolitanTransitAuthority { public static int Main(string[] args) { Title = "States Statistics"; WriteLine("States Statistics"); Collection states = new Collection(); int numberofItems = states.Count; WriteLine("----------------------------------"); WriteLine("The list contains {0} items", @numberofItems); WriteLine("=================================="); return 1010; } }
This would produce:
States Statistics ---------------------------------- The list contains 0 items ================================== Press any key to continue . . .
Introduction to Lists Operations
Adding a Value to a Collection
The primary operation performed on a collection consists of adding an item to it, and then adding other items. The easiest way to do this is to add an item at the end of the existing collection.
To add an item to the collection, because an array has (or is supposed to have) a fixed number of items, you should first check whether the list is already full. For an array-based list, the collection is full if its count of items is equal to the maximum number of items it can hold. If the collection can still receive at least one item, you can add the item at the end of the list and increase the count by one. Once you have a means of adding items to the list, you can effectively create a list of items. Here is how this can be done:
public class Collection { // This is the size of the collection private int size; private string[] items; #region This section is used to set up the collection public Collection() { size = 0; items = new string[10]; } // This represents the number of items in the collection public int Count { get { return size; } } #endregion #region Operations on the collection // Adds a new item to the list if the list is not full // Increases the number of items in the list // Returns true if the item was added, otherwise returns false public bool Add(string item) { // Make sure the list is not yet full if (this.size < 10) { // Since the list is not full, add the item at the end this.items[this.size] = item; // Increase the count and return the new position this.size++; // Indicate that the item was successfully added return true; } // If the item was not added, return false; return false; } #endregion }
Here is an example:
public class StatesStatistics
{
public static int Main(string[] args)
{
Collection Brazil = new Collection();
Brazil.Add("Pernambuco");
Brazil.Add("Maranhão");
Brazil.Add("Acre");
Brazil.Add("Ceará");
}
}
Getting an Item From a Collection
After adding items to a collection, you can retrieve them, for any reason. To retrieve an item, you can locate it by its position, especially if you had created/started the collection from an array. Having this index, you can check whether the position specified is negative or higher than the current count of items. If it is, there is nothing much to do since the index would be wrong. If the index is in the right range, you can retrieve its corresponding item. The method to do this can be implemented as follows:
public class Collection
{
. . . No Change
#region Operations on the collection
. . . No Change
// This method retrieves an item from the list based on the specified index
public string Get(int pos)
{
// Make sure the index is in the range
if (pos >= 0 && pos <= size)
return items[pos];
// If the index was wrong, return 0
return string.Empty;
}
#endregion
}
Here is an example of calling the method repeatedly in a loop:
using static System.Console; public class Collection { // This is the size of the collection private int size; private string[] items; #region This section is used to set up the collection public Collection() { size = 0; items = new string[10]; } // This represents the number of items in the collection public int Count { get => size; } #endregion #region Operations on the collection // Adds a new item to the list if the list is not full // Increases the number of items in the list // Returns true if the item was added, otherwise returns false public bool Add(string item) { // Make sure the list is not yet full if (this.size < 10) { // Since the list is not full, add the item at the end this.items[this.size] = item; // Increase the count and return the new position this.size++; // Indicate that the item was successfully added return true; } // If the item was not added, return false; return false; } // This method retrieves an item from the list based on the specified index public string Get(int pos) { // Make sure the index is in the range if (pos >= 0 && pos <= size) return items[pos]; // If the index was wrong, return 0 return string.Empty; } #endregion } public class MetropolitanTransitAuthority { public static int Main(string[] args) { Title = "States Statistics"; WriteLine("States Statistics"); Collection Brazil = new Collection(); Brazil.Add("Pernambuco"); Brazil.Add("Maranhão"); Brazil.Add("Acre"); Brazil.Add("Ceará"); Brazil.Add("Rio Grande do Norte"); Brazil.Add("São Paulo"); Brazil.Add("Goiás"); Brazil.Add("Mato Grosso"); Brazil.Add("Santa Catarina"); Brazil.Add("Pernambuco"); int numberofItems = Brazil.Count; WriteLine("--------------------------"); WriteLine("The list contains {0} items", @numberofItems); WriteLine("--------------------------"); for (int i = 0; i < Brazil.Count; i++) WriteLine(Brazil.Get(i)); WriteLine("=================================="); return 1010; } }
This would produce:
States Statistics -------------------------- The list contains 10 items -------------------------- Pernambuco Maranhao Acre Ceará Rio Grande do Norte Sao Paulo Goiás Mato Grosso Santa Catarina Pernambuco ================================== Press any key to continue . . .
Inserting an Item in the List
Inserting a new item in the collection allows you to add one at a position of your choice. To insert an item in the list, you must provide the new item and the desired position. Before performing this operation, you must check two things. First, the list must not be empty because if it is, then there is no way to insert an item (you insert something between two things, not something in nothing). Second, the specified position must be in the allowed range. Here is an example of performing this operation:
using System; using static System.Console; public class Exercise { public static int Main(string[] args) { Title = "States Statistics"; WriteLine("States Statistics"); Collection Brazil = new Collection(); Brazil.Add("Pernambuco"); Brazil.Add("Maranhão"); Brazil.Add("Acre"); Brazil.Add("Ceará"); Brazil.Add("Rio Grande do Norte"); Brazil.Add("São Paulo"); Brazil.Add("Goiás"); Brazil.Add("Mato Grosso"); Brazil.Add("Santa Catarina"); int numberofItems = Brazil.Count; WriteLine("----------------------------------"); WriteLine("The list contains {0} items", @numberofItems); for (int i = 0; i < Brazil.Count; i++) WriteLine(Brazil.Get(i)); Brazil.Insert("Espírito Santo", 5); WriteLine("----------------------------------"); WriteLine("The list contains {0} items", Brazil.Count); for (int i = 0; i < Brazil.Count; i++) WriteLine(Brazil.Get(i)); WriteLine("=================================="); return 10; } } public class Collection { // This is the size of the collection private int size; // This is an array that will hold the items of this collection private string[] items; #region This section is used to set up the collection // This constructor will be used to initialize the list public Collection() { // When the list starts, it is empty: it's size is 0 size = 0; // Start the list with 0 item. items = new string[0]; } // This read-only property represents the number of items in the collection public int Count { get { return size; } } #endregion #region Operations on the collection /* This method adds a new item to the list. The item is added at the ebd of the list: * 1. First, since the list is an array, increase the array by 1 item * 2. Set the new item in the last position * 3. Return the index of the new item. */ public int Add(string item) { // First, since the collection is created from an array, increase the array by 1 item Array.Resize(ref items, items.Length + 1); // Set the new item in the last position items[size++] = item; // Return the index of the new item return size; } // This method retrieves an item from the list based on the specified index public string Get(int pos) { // Make sure the index is in the range if (pos >= 0 && pos <= size) return items[pos]; // If the index was wrong, return 0 return string.Empty; } /* This method is used to insert a new item somewhere inside the list. * Of course, the list must not be empty. */ public void Insert(string item, int pos) { /* Before performing this operation, check the number of items in the list. * If the list is empty, don't do nothing. */ if( size == 0 ) return; // Make sure the position that was given is positive. Otherwise, don't do nothing. if( pos < 0 ) return; /* Make sure the position that was given is not greater than the * size of the collection. If that's the case, don't do nothing. */ if( pos > size ) return; // Before inserting the new item, since the collection is created from an array, increase the array by 1 item Array.Resize(ref items, items.Length + 1); /* Visit each item from the end of the list to the position of the new item. * From the indicated position of the new item, move each existing item one position to the end of the list. */ for (int i = size; i > pos - 1; i--) items[i] = items[i - 1]; /* The above operation was meant to create an empty space in the new position. * Now that we have room, put the new item in the position created. */ items[pos - 1] = item; // Increase the number of items in the collection by 1. size++; } #endregion }
This would produce:
States Statistics ---------------------------------- The list contains 9 items Pernambuco Maranhao Acre Ceará Rio Grande do Norte Sao Paulo Goiás Mato Grosso Santa Catarina ---------------------------------- The list contains 10 items Pernambuco Maranhao Acre Ceará Espírito Santo Rio Grande do Norte Sao Paulo Goiás Mato Grosso Santa Catarina ================================== Press any key to continue . . .
Removing an Item From a Collection
Another operation you can perform on a collection consists of deleting an item. This is also referred to as removing the item. To delete an item from a collection, you can provide its position. Before performing the operation, you can (should/must) first check that the specified position is valid. The method to perform this operation can be defined as follows:
using System; using static System.Console; public class Collection { // This is the size of the collection private int size; // This is an array that will hold the items of this collection private string[] items; #region This section is used to set up the collection // This constructor will be used to initialize the list public Collection() { // When the list starts, it is empty: it's size is 0 size = 0; // Start the list with 0 item. items = new string[0]; } // This read-only property represents the number of items in the collection public int Count { get { return size; } } #endregion #region Operations on the collection /* This method adds a new item to the list. The item is added at the ebd of the list: * 1. First, since the list is an array, increase the array by 1 item * 2. Set the new item in the last position * 3. Return the index of the new item. */ public int Add(string item) { // First, since the collection is created from an array, increase the array by 1 item Array.Resize(ref items, items.Length + 1); // Set the new item in the last position items[size++] = item; // Return the index of the new item return size; } // This method retrieves an item from the list based on the specified index public string Get(int pos) { // Make sure the index is in the range if (pos >= 0 && pos <= size) return items[pos]; // If the index was wrong, return 0 return string.Empty; } /* This method is used to insert a new item somewhere inside the list. * Of course, the list must not be empty. */ public void Insert(string item, int pos) { /* Before performing this operation, check the number of items in the list. * If the list is empty, don't do nothing. */ if( size == 0 ) return; // Make sure the position that was given is positive. Otherwise, don't do nothing. if( pos < 0 ) return; /* Make sure the position that was given is not greater than the * size of the collection. If that's the case, don't do nothing. */ if( pos > size ) return; // Before inserting the new item, since the collection is created from an array, increase the array by 1 item Array.Resize(ref items, items.Length + 1); /* Visit each item from the end of the list to the position of the new item. * From the indicated position of the new item, move each existing item one position to the end of the list. */ for (int i = size; i > pos - 1; i--) items[i] = items[i - 1]; /* The above operation was meant to create an empty space in the new position. * Now that we have room, put the new item in the position created. */ items[pos - 1] = item; // Increase the number of items in the collection by 1. size++; } // This method removes an item from the list // First check that the specified position is valid //-- Delete the item at that position and decrease the count --// public bool Delete(int pos) { // Make sure the position specified is in the range if (pos >= 0 && pos <= size) { // Since there is room, starting at the specified position, // Replace each item by the next for (int i = pos; i < size; i++) items[i - 1] = items[i]; // Since an item has been removed, decrease the count size--; // Indicate that the operation was successful return true; } // Since the position was out of range, return false return false; } #endregion } public class Exercise { public static int Main(string[] args) { Title = "States Statistics"; WriteLine("States Statistics"); Collection Brazil = new Collection(); Brazil.Add("Pernambuco"); Brazil.Add("Maranhão"); Brazil.Add("Acre"); Brazil.Add("Ceará"); Brazil.Add("Peyton"); Brazil.Add("Rio Grande do Norte"); Brazil.Add("São Paulo"); Brazil.Add("Goiás"); Brazil.Add("Mato Grosso"); Brazil.Add("Santa Catarina"); int numberofItems = Brazil.Count; WriteLine("----------------------------------"); WriteLine("The original list contains {0} items", @numberofItems); for (int i = 0; i < Brazil.Count; i++) WriteLine(Brazil.Get(i)); Brazil.Insert("Espírito Santo", 3); WriteLine("----------------------------------"); WriteLine("After inserting an item, the list now contains {0} items", Brazil.Count); for (int i = 0; i < Brazil.Count; i++) WriteLine(Brazil.Get(i)); Brazil.Delete(7); WriteLine("----------------------------------"); WriteLine("After removing an item from the list, the list now contains {0} items", Brazil.Count); for (int i = 0; i < Brazil.Count; i++) WriteLine(Brazil.Get(i)); WriteLine("=================================="); return 10; } }
This would produce:
States Statistics ---------------------------------- The original list contains 10 items Pernambuco Maranhao Acre Ceará Peyton Rio Grande do Norte Sao Paulo Goiás Mato Grosso Santa Catarina ---------------------------------- After inserting an item, the list now contains 11 items Pernambuco Maranhao Espírito Santo Acre Ceará Peyton Rio Grande do Norte Sao Paulo Goiás Mato Grosso Santa Catarina ---------------------------------- After removing an item from the list, the list now contains 10 items Pernambuco Maranhao Espírito Santo Acre Ceará Peyton Sao Paulo Goiás Mato Grosso Santa Catarina ================================== Press any key to continue . . .
A Collection of Items
Introduction
Like an array, a collection is a series of items of the same type. The particularity with creating an array is that you must know and specify in advance the number of items that will make up the list. There are times when you don't know or you can't predict the number of items of the list. For this reason, you may want to create the list for which you don't specify the maximum number of items but you allow the user of the list to add, locate, or remove items at will.
Before creating a list, you probably should first decide or define what the list would be made of.
Starting a Collection
After deciding what each item of the list would be made of, you can create a class that would manage the list. This class would be responsible for all operations that can be performed on the list. If the list will be made of primitive values, you can directly create a field of the desired type. Here is an example:
public class Collection { }
Here is an example of declaring a variable of this clas:
public class Exercise
{
public static int Main(string[] args)
{
Collection storeItems = new Collection();
}
}
The Type of the Items of a Collection
If the list will be made of objects, you can first create a class that specifies the types of items and then declare its variable in the list class. Here is an example:
namespace Combinations { public class Item { public string Value; } public class Collection { private Item Sample; } }
Here is an example of specifying a value of an item of a collection:
public class Exercise
{
public static int Main(string[] args)
{
Combinations.Collection storeItems = new Combinations.Collection();
Combinations.Item itm = new Combinations.Item();
itm.Value = "Floral Blouson Midi Dress";
}
}
When creating a list, you should keep track of the number of items in the list. To do this, you can create a property that holds the number. The value of this property would increase as the items are added to the list and the value would decrease when an item is removed from the list. Here is how this can be done:
public class Item { public string Value; } public class Collection { int size; public Collection() { size = 0; } public int Count { get { return size; } } }
Here is an example of getting the number of items of a collection:
using static System.Console; public class Item { public string Value; } public class Collection { int size; public Collection() { size = 0; } public int Count { get { return size; } } } public class Exercise { public static int Main(string[] args) { Title = "Department Store"; WriteLine("Department Store"); Collection storeItems = new Collection(); Item itm = new Item(); itm.Value = "Floral Blouson Midi Dress"; WriteLine("-------------------"); WriteLine("Number of Items: {0}", storeItems.Count); WriteLine("=================================="); return 10; } }
This would produce:
Department Store ------------------- Number of Items: 0 ================================== Press any key to continue . . .
The Beginning of a Collection
A typical collection grows or shrinks regularly. When creating the list, you don't need to predict the maximum number of items that will be added to the list. When a list starts, it is empty. To specify this, you should declare a primary member variable. Although you can call it anything, it is usually called Head:
The head member can be made private if you don't intend to access it outside the class. If you want clients of the class to access it, you can make it public. Here is an example:
public class Item { public string Value; } public class Collection { int size; public Item Head; public Collection() { size = 0; Head = null; } public int Count => size; }
Linking the Items of a Collection
If the items of a collection are not indexed, you must provide a mechanism to locate an item. To do this, you can use a starting point that determines the beginning of the list. Then, to locate an item, you can check whether another item follows that starting point:
If no item follows an item, either you are at the end of the list or the list is empty.
To be able to scan a list from one item to another, you can declare a field. Although this member variable can be called anything, for the sake of clarity, you should call it Next. The field is the same type as its class. Here is an example:
public class Item
{
public string Value;
public Item Next;
}
Operations on a Collection
Adding an Item
Since a list is fundamentally empty when it starts, the primary operation you can perform on a list is to add a new item to it. In order to indicate that you want to add an item to the list, you can create a method that receives an item as argument. For the return type, you have two main options. Because the main job of this method is to add a new item, which it hardly fails to do if you implement it right, it can be defined as void. Alternatively, you can make it return the position of the new item in the list. Here is an example:
public class Item
{
public string Value;
public Item Next;
}
public class Collection
{
int size;
private Item Sample;
public Item Head;
public Collection()
{
size = 0;
Head = null;
}
public int Count
{
get { return size; }
}
public int Add(Item nItem)
{
Item sample = nItem;
sample.Next = this.Head;
this.Head = sample;
return size++;
}
}
Here are examples of calling this method:
using static System.Console;
public class Item
{
public string Value;
public Item Next;
}
public class Collection
{
int size;
private Item Sample;
public Item Head;
public Collection()
{
size = 0;
Head = null;
}
public int Count
{
get { return size; }
}
public int Add(Item nItem)
{
Item sample = nItem;
sample.Next = this.Head;
this.Head = sample;
return size++;
}
}
public class Exercise
{
public static int Main(string[] args)
{
Title = "Department Store";
WriteLine("Department Store");
Collection storeItems = new Collection();
Item itm = new Item();
itm.Value = "Floral Blouson Midi Dress";
storeItems.Add(itm);
itm = new Item();
itm.Value = "Heathered Sweatpants";
storeItems.Add(itm);
itm = new Item();
itm.Value = "Bellow Leather Knee-High Boots";
storeItems.Add(itm);
WriteLine("-------------------");
WriteLine("Number of Items: {0}", storeItems.Count);
WriteLine("=================================");
return 20;
}
}
This would produce:
Department Store ------------------- Number of Items: 3 ================================== Press any key to continue . . .
Getting an Item from a Collection
To locate and get an item of a collection, you can create a method that takes an index as argument. The method would examine the argument with regards to the number of items in the list to make sure the argument's value is in the range of the current items of the list. If the number is too low or too high, the method can return null, 0, or throw an exception. If the number is in the range, the method can return the item at that position. Here is an example:
public class Item
{
public string Value;
public Item Next;
}
public class Collection
{
. . . No Change
public Item Get(int index)
{
Item current = this.Head;
for (int i = this.size - 1; i > index && current != null; i--)
current = current.Next;
return current;
}
}
Here is an example of getting the items of a collection:
using static System.Console; public class Item { public string Value; public Item Next; } public class Collection { int size; private Item Sample; public Item Head; public Collection() { size = 0; Head = null; } public int Count { get { return size; } } public int Add(Item nItem) { Item sample = nItem; sample.Next = this.Head; this.Head = sample; return size++; } public Item Get(int index) { Item current = this.Head; for (int i = this.size - 1; i > index && current != null; i--) current = current.Next; return current; } } public class Exercise { public static int Main(string[] args) { Title = "Department Store"; WriteLine("Department Store"); Collection storeItems = new Collection(); Item itm = new Item(); itm.Value = "Floral Blouson Midi Dress"; storeItems.Add(itm); itm = new Item(); itm.Value = "Heathered Sweatpants"; storeItems.Add(itm); itm = new Item(); itm.Value = "Bellow Leather Knee-High Boots"; storeItems.Add(itm); itm = new Item(); itm.Value = "Pleated A-Line Skirt"; storeItems.Add(itm); itm = new Item(); itm.Value = "Long Sleeve Blouse"; storeItems.Add(itm); WriteLine("--------------------------------------------"); for (int i = 0; i < @storeItems.Count; i++) WriteLine("Store Item: {0}", storeItems.Get(i).Value); WriteLine("--------------------------------------------"); WriteLine("Number of Items: {0}", storeItems.Count); WriteLine("============================================"); return 10; } }
This would produce:
Department Store -------------------------------------------- Store Item: Floral Blouson Midi Dress Store Item: Heathered Sweatpants Store Item: Bellow Leather Knee-High Boots Store Item: Pleated A-Line Skirt Store Item: Long Sleeve Blouse -------------------------------------------- Number of Items: 5 ============================================ Press any key to continue . . .
Removing an Item
Deleting an item consists of removing it from the collection. There are various issues involved and different ways this can be done. One way is to remove the first item (the head) of the collection. Always make sure you perform other routine operations such as decrementing the count of items in the list. Here is an example of how this can be done:
using static System.Console; public class Item { public string Value; public Item Next; } public class Collection { int size; public Item Head; public Collection() { size = 0; Head = null; } public int Count { get { return size; } } public Item Get(int index) { Item current = Head; for (int i = this.size - 1; i > index && current != null; i--) current = current.Next; return current; } public void Add(Item nItem) { Item sample = nItem; sample.Next = Head; Head = sample; size++; } public void Delete() { DeleteFirst(); } public void DeleteFirst() { if (Head == null) { WriteLine("The list is empty"); return; } Item Current = Head; Current.Next = Head.Next; size--; return; } } public class Exercise { public static int Main(string[] args) { Title = "Department Store"; WriteLine("Department Store"); Collection storeItems = new Collection(); Item itm = new Item(); itm.Value = "Floral Blouson Midi Dress"; storeItems.Add(itm); itm = new Item(); itm.Value = "Heathered Sweatpants"; storeItems.Add(itm); itm = new Item(); itm.Value = "Bellow Leather Knee-High Boots"; storeItems.Add(itm); itm = new Item(); itm.Value = "Pleated A-Line Skirt"; storeItems.Add(itm); itm = new Item(); itm.Value = "Long Sleeve Blouse"; storeItems.Add(itm); WriteLine("--------------------------------------------"); for (int i = 0; i < @storeItems.Count; i++) WriteLine("Store Item: {0}", storeItems.Get(i).Value); WriteLine("--------------------------------------------"); WriteLine("Number of Items: {0}", storeItems.Count); storeItems.Delete(); WriteLine("--------------------------------------------"); for (int i = 0; i < @storeItems.Count; i++) WriteLine("Store Item: {0}", storeItems.Get(i).Value); WriteLine("--------------------------------------------"); WriteLine("Number of Items: {0}", storeItems.Count); WriteLine("============================================"); return 10; } }
This would produce:
Department Store -------------------------------------------- Store Item: Floral Blouson Midi Dress Store Item: Heathered Sweatpants Store Item: Bellow Leather Knee-High Boots Store Item: Pleated A-Line Skirt Store Item: Long Sleeve Blouse -------------------------------------------- Number of Items: 5 -------------------------------------------- Store Item: Heathered Sweatpants Store Item: Bellow Leather Knee-High Boots Store Item: Pleated A-Line Skirt Store Item: Long Sleeve Blouse -------------------------------------------- Number of Items: 4 ============================================ Press any key to continue . . .
Checking Whether a Collection Contains an Item
One of the operations usually performed on a list is to find out whether a list contains a certain item. One way you can do this is to completely define an item and pass it to the list. Only if the (exact) item is found in the list would it be recognized. Here is an example:
using static System.Console; public class Item { public string Value; public Item Next; } public class Collection { int size; public Item Head; public Collection() { size = 0; Head = null; } public int Count { get { return size; } } public Item Get(int index) { Item current = Head; for (int i = this.size - 1; i > index && current != null; i--) current = current.Next; return current; } public void Add(Item nItem) { Item sample = nItem; sample.Next = Head; Head = sample; size++; } /*public void Delete() { DeleteFirst(); } public void DeleteFirst() { if (Head == null) { WriteLine("The list is empty"); return; } Item Current = Head; Current.Next = Head.Next; size--; return; }*/ public bool Delete(bool val) { if (Head == null) { return false; } Item current = Head.Next; Head.Next = current; size--; return true; } public bool Contains(Item obj) { Item current = new Item(); if (obj == null) return false; for (current = Head; current != null; current = current.Next) { if (current.Value == obj.Value) return true; } return false; } } public class Exercise { public static int Main(string[] args) { Title = "Department Store"; WriteLine("Department Store"); Collection storeItems = new Collection(); Item itm = new Item(); itm.Value = "Floral Blouson Midi Dress"; storeItems.Add(itm); itm = new Item(); itm.Value = "Heathered Sweatpants"; storeItems.Add(itm); itm = new Item(); itm.Value = "Bellow Leather Knee-High Boots"; storeItems.Add(itm); itm = new Item(); itm.Value = "Pleated A-Line Skirt"; storeItems.Add(itm); itm = new Item(); itm.Value = "Long Sleeve Blouse"; storeItems.Add(itm); itm = new Item(); itm.Value = "Toast Girls' Two-Tab Pleated Scooter Skirt"; storeItems.Add(itm); WriteLine("--------------------------------------------"); for (int i = 0; i < storeItems.Count; i++) WriteLine("Store Item: {0}", storeItems.Get(i).Value); WriteLine("--------------------------------------------"); WriteLine("Number of Items: {0}", storeItems.Count); Item search = new Item(); search.Value = "Bellow Leather Knee-High Boots"; bool present = storeItems.Contains(search); if (present == true) WriteLine("The collection contains: {0}", search.Value); else WriteLine("The collection doesn't contain: {0}", search.Value); search = new Item(); search.Value = "Girls and Toddlers Switchback II Waterproof Jacket"; present = storeItems.Contains(search); if (present == true) WriteLine("The collection contains: {0}", search.Value); else WriteLine("The collection doesn't contain: {0}", search.Value); WriteLine("============================================"); return 10; } }
This would produce:
Department Store -------------------------------------------- Store Item: Floral Blouson Midi Dress Store Item: Heathered Sweatpants Store Item: Bellow Leather Knee-High Boots Store Item: Pleated A-Line Skirt Store Item: Long Sleeve Blouse Store Item: Toast Girls' Two-Tab Pleated Scooter Skirt -------------------------------------------- Number of Items: 6 The collection contains: Bellow Leather Knee-High Boots The collection doesn't contain: Girls and Toddlers Switchback II Waterproof Jack et ============================================ Press any key to continue . . .
|
||
Previous | Copyright © 2008-2021, FunctionX | Next |
|