sam_the_man
sam_the_man

Reputation: 21

Make a method that contains a linear search?

I'm new to programmning and I'm taking a course to learn the basics in c#. Right now I'm doing a console application that are supposed to work as a blog. In the application the user should be able to write a new post, show written posts and search for written posts. The application is supposed to be a list that contains arrays.

I'm almost finished with the application but I want to make a method for the linear search that searches for the written blogposts but I cant get it to work. Here's the code for the linear search:

case 3:
    Console.Write("Write the title for the post you are searching for: ");
    string searchedWord = Console.ReadLine();
    bool search = false;

    for (int i = 0; i < myBlog.Count; i++)
    {
        if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
        {
             search = true;                        
             Console.WriteLine("\nHe post you are looking for exists in the blog:");
             Console.WriteLine("\nTitle: " + myBlog[i][0] +
                               "\nPost: " + myBlog[i][1] +
                               "\n\nPress enter to return to the menu...");
        }

     }
     if (search == false)
     {
         Console.WriteLine("The searched word wasn't found. Press enter to return to the menu...");
     }
     break;

I made a try creating a method for it but I'm doing wrong, can somebody please tell me how to do it?

static string BlogSearch(List<string[]> myBlog, string searchedWord)
{
     for (int i = 0; i < myBlog; i++)
     {
          if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
                    return i;
     }
     return -1;
}

Upvotes: 1

Views: 344

Answers (1)

Fildor
Fildor

Reputation: 16148

If you are allowed to use Linq, you can do

using System.Linq;
//....

static string[] BlogSearch(List<string[]> myBlog, string searchedWord)
{
    // "give me from myBlog ...
    //  the first element, that fits the criteria OR
    //  default if such an element is not in the list"
    return myBlog.FirstOrDefault(x => x[0].Contains(searchedWord, StringComparison.OrdinalIgnoreCase));
}

See it in action in a Fiddle

Mind that this returns default(string) (which is null) if the searchedWord is not found.

I guess you are using string[] because your class (pun intended) has not come across the concept of classes, yet. So I won't go into that. Just so much: usually, you would model your blog data into a class with specific properties. And later on, you would probably want to keep the data in a Database instead of memory ... but all that is not really related to the problem at hand.

If you are NOT allowed to use Linq:

static string[] BlogSearch(List<string[]> myBlog, string searchedWord)
{
    for( int i = 0; i < myBlog.Count; i++ )
    {
        if( myBlog[i][0].Contains(searchedWord, StringComparison.OrdinalIgnoreCase))
        {
            return myBlog[i];
        }
    }
    return null;
}

Which is basically the same as the Linq version just coded out explicitly.

See it in action in a Fiddle.


Usage

// ... case 3: ...
var result = BlogSearch(myBlog, searchedWord);
if( result is null )
{
    Console.WriteLine("The searched word wasn't found. Press enter to return to the menu...");
}
else
{
    Console.WriteLine("\nThe post you are looking for exists in the blog:");
    Console.WriteLine("\nTitle: " + result[0] +
                      "\nPost: " + result[1] +
                      "\n\nPress enter to return to the menu...");
}
break;

Some hints for you concerning your code:

       //    You expect to be returning `string`
       //    but all return statements return `int`.
       // vv What you actually need is `string[]`, though.
static string BlogSearch(List<string[]> myBlog, string searchedWord)
{
     //                  vv that's a `List<T>`, so you need `myBlog.Count` here
     for (int i = 0; i < myBlog; i++)
     {
          // Two caveats:
          // 1. _Exact_ match
          // 2. `ToUpper` does not always work correctly.
          //    It is advised to use overloads with `StringComparison` argument
          if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
                    return i;
     }
     return -1;
}

Upvotes: 2

Related Questions