C# Custom LinkedList FindItems() method - Learning C# - Part 6

In Part 1 of this series, we created a console application and an abstract class. In Part 2 we setup our LinkedList derived class and defined our properties and setup our constructor. In Part 3, we defined our Push and Pop methods. We implemented both a PopLifo and PopFifo method. In part 4 we defined our PrintLifo method to print nodes from the top of the stack. We also discussed C# Operators. In Part 5 we defined a PrintFifo() method, which used a GetNode() helper method to find specific nodes, allowing us to print nodes from the bottom of the stack.

In this article, we will create a FindItems() method which will print a listing to the screen of all items based on the category or item name.


   public bool FindItems(string category, string item = "")
   {
   LinkedList CurrentNode = new LinkedList();
   bool boolSuccess = false;   // initialize
   if (category == "" && item == "")
   {
   Console.WriteLine("\nYou must provide a category or item to begin the search.");
   return boolSuccess;
   }
First we define our FindItems method and pass the category by name. Our "item" parameter is an optional parameter, indicated so by defining the default value: '= ""'. This means that the user may pass in a value or not use it at all as in: FindItems(categoryname,itemname) vs. FindItems(categoryname).

If our category and our item are both blank, we send a message to the screen and return to the calling method. If not, we write a message to the screen indicating that we are in search mode and what the two search criteria are.

   Console.WriteLine("\nSearch Criteria: '{0}' and '{1}'\n", category, item);
   for (CurrentNode = Head; CurrentNode != null; CurrentNode = CurrentNode.Next)
   {
   // if it finds the item or the category, print the item
   if ((CurrentNode.Item() == item) ||
   (CurrentNode.Category() == category))
   {
   Console.WriteLine("Found Category: {0} Item: {1}", 
CurrentNode.Category(), CurrentNode.Item()); boolSuccess = true; } } return boolSuccess; } }



In this "for" loop, we start with the Head node, and as long as the node is not null, we loop through the nodes, reassigning our current node to the node as stored in the "Next" node. As we loop through the nodes, we see if the value of the item or category match the search criteria, and if so, we print the node values to the screen. If an item is found, we set the boolSuccess value to true and at the end of the method, we pass this back to the calling method.

In our next article, we will look at our Main() program and how to use our new LinkedList class.


[CSLINKEDLIST]

No Comments