C# Custom LinkedList FindItems() method - Learning C# - Part 6
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.
- Download Source Code on CodePlex: CSLinkedList.zip
- C# Custom LinkedList Console Application and Abstract Base Class and Method - Learning C# - Part 1
- C# Custom LinkedList Derived Classes, Constructor Initializations - Learning C# - Part 2
- C# Custom LinkedList Push and Pop Methods - Learning C# - Part 3
- C# Custom LinkedList PrintLifo method and C# Operators - Learning C# - Part 4
- C# Custom LinkedList PrintFifo method and GetNode by Position - Learning C# - Part 5
- C# Custom LinkedList FindItems() method - Learning C# - Part 6
- C# Custom LinkedList Main() method - Learning C# - Part 7
[CSLINKEDLIST]