0

I'm trying to create a search method in C# and I am stuck.

This is my method that I want to use to search for the array values inside my List object:

public void Search()
        {
            Console.Write("\tKeyword: ");
            string keyword = Console.ReadLine();

            List<string> searchResults = new List<string>();

            for (int a = 0; a < log.Count; a++)
            {
                foreach (string item in log[a])
                {
                    if (item.Contains(keyword))
                        searchResults.Add(item);
                }
            }

            Console.WriteLine("Search Results: ");
            for (int b = 0; b < searchResults.Count; b++)
            {
                Console.WriteLine("\t{0}\t{1}\t\t{2}", searchResults[b][0], searchResults[b][1], searchResults[b][2]);
            }

        }

This is my List that I want to search through:

private List<string[]> log = new List<string[]>();

This is how I add arrays into the List:

string[] arrOfLog = new string[4] {
            String.Format("{0:yyyy-MM-dd}", localDate),
            title,
            desc,
            null
        };

        log.Add(arrOfLog);

What can I do to search for title and description values?

I get the exception:

Object reference not set to an instance of an object.

Osama AbuSitta
  • 3,918
  • 4
  • 35
  • 51
De2o
  • 3
  • 3

2 Answers2

0

You can do this after creating a model class ,

public class model
{
    string localDate { get; set; }
    string title { get; set; }
    string desc { get; set; }
}

then using that you can search those separately.

This is the full code

public void Search()
{
    Console.Write("\tKeyword: ");
    string keyword = Console.ReadLine();

    List<string> moList = new List<string>();
    foreach ( var item in log )
    {
        model mo = new model();
        mo.localDate = log[0];
        mo.title = log[1];
        mo.desc = log[2];
    }

    List<string> searchResults = new List<string>();

    for (int a = 0; a < moList.Count; a++)
    {
        foreach (model item in moList[a])
        {
            if (item.title.Contains(keyword) || item.desc.Contains(keyword)){
                 searchResults.Add(item);
            }
        }
    }

    Console.WriteLine("Search Results: ");
    for (int b = 0; b < searchResults.Count; b++)
    {
         Console.WriteLine("\t{0}\t{1}\t\t{2}", searchResults[b][0], searchResults[b][1], searchResults[b][2]);
    }

}
Thili77
  • 1,061
  • 12
  • 20
0

you could write item?.Contains(keyword) ?? false instead of item.Contains(keyword)
the ? does not call Contains if item is null, but you get null if item is null.
the ?? tells the compiler to use false if item is null.

Matz Reckeweg
  • 31
  • 1
  • 4