DatDudeAgain DatDudeAgain - 2 months ago 8
C# Question

Searching in a list for a specified string

I am trying to search a List of strings. I want to be able to return any found results that include information from a string. For example:

(I already have a list with values) List strings contains


"dog", "cat", "doghouse", "doge", "mouse"


I want a way to check a string, for example:

string dog = "dog"


And return the values:


"dog", "doghouse", "doge"


This is what I have so far, at least the portion I need help on.

Console.WriteLine("What would you like to search for (Title: Full Title; Author: first, last): ");
search = Console.ReadLine();

var results = bookList.Where(x => x.Contains(search)).ToList();
if (results != null)
{
Console.WriteLine(results);
//i--;
search = String.Empty;
clearvars results;
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
continue;
}


search
is an empty string

bookList
is my
List<string>


i
is just a counter, not really necessary for this

I am doing this whole thing in a
for
loop if that changes anything.

Answer

You need to iterate on every element of the result (the results variable).

Console.WriteLine("What would you like to search for (Title: Full Title; Author: first, last): ");
search = Console.ReadLine();
var results = bookList.Where(x => x.Contains(search)).ToList();
if (results != null)
{
    foreach (var result in results)
    {
        Console.WriteLine(result);
    }
    Console.WriteLine("Press Enter to continue");
    Console.ReadLine();
}

You need to iterate on results because it is a List. When you pass a list to Console.WriteLine() like this: Console.WriteLine(results) the method ToString() is called on results. Calling ToString() on a List returns: System.Collections.Generic.List1[System.String] which is what you have probably seen on you console.

System.Collections.Generic.List1[System.String] is a string representation of a list object, but what you're realy interested in are the elements of the list. This is why you need to iterete on the list and print each element separatly.

You could also join all elements of the results list into one string and then print it:

var allResultsInOneString = string.Join(", ", results);
Console.WriteLine(allResultsInOneString);