Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this video, we'll review the solution to the first challenge and introduce our second challenge—using a `foreach` loop to implement a method that'll give us a way to find a single item in our Media Library.
Instructions
2nd Challenge
-
Add a method named
FindItem()
to the MediaLibrary class.- The method should return a MediaType item and define a parameter of type
string
namedcriteria
. - Use a
foreach
loop to loop through the items array contained within the MediaLibrary class. - Return the item whose
Title
property contains the providedcriteria
string parameter value.
- The method should return a MediaType item and define a parameter of type
-
In the Program.cs file, search the media library for an item by calling the
FindItem()
method.- If an item is found, pass it into a call to the static MediaLibrary
DisplayItem()
method. - If an item isn't found, write the message "Item not found!" to the console.
- If an item is found, pass it into a call to the static MediaLibrary
Finding a String Within Another String
There are many ways in C# to test if a string is contained within another string. Here's one approach that makes use of the String.Contains()
method.
var songTitle = "Row Row Row Your Boat";
Console.WriteLine(songTitle.Contains("Your")); // Outputs "true" to the console
Console.WriteLine(songTitle.Contains("your")); // Outputs "false" to the console
This examples demonstrates one potential issue with this approach: the Contains()
method is case-sensitive. As a workaround, we can call ToLower()
on both the search criteria and item title.
var songTitle = "Row Row Row Your Boat";
Console.WriteLine(songTitle.ToLower().Contains("Your".ToLower())); // Outputs "true" to the console
Console.WriteLine(songTitle.ToLower().Contains("your")); // Outputs "true" to the console
By forcing all of the characters to lowercase, we're eliminating any case-sensitivity issues.
Here's the documentation on both the Contains()
and ToLower()
methods:
Help
If you get stuck on any of the following topics or simply need a refresher, click on a topic in list below to view the associated video in the C# Objects course.
You need to sign up for Treehouse in order to download course files.
Sign up