简体   繁体   中英

Searching in a List with Linq

I am trying to search for objects that include a certain string in a field of the object(Title). Afterwards I would like to fill a list with the objects that include that string. My list is not getting filled up.

    public void SearchMovies(String searckhQuery) {
    Console.WriteLine(searckhQuery);
    if(searckhQuery == null) {
        Console.WriteLine("yesbaby");
    } else {
        Console.WriteLine("itworks");
        List<MovieViewModel> searchMovieList = new List<MovieViewModel>();
        movieList.Where(m => m.Title.Contains(searckhQuery));
        movieList.Select(m => searchMovieList);
        movieList = searchMovieList;
    }
}

Thanks for the help in advance!

You need to understand how the linq queries work. The Where and Select return a new collection. It will not filter down the same list object. The syntax would be:

searchMovieList = movieList.Where(m => m.Title.Contains(searckhQuery)).ToList();

If the MovieViewModel and movieList is a collection of different types, then we will need to use Select and assign the properties as needed like:

searchMovieList = movieList.Where(m => m.Title.Contains(searckhQuery))
                          .Select(m => new MovieViewModel() 
                                       {
                                          Title = m.Title,
                                          .....
                                       }).ToList();

If both are of same type then it can be made more simple:

movieList = movieList.Where(m => m.Title.Contains(searckhQuery)).ToList();

Where and Select are not methods that manipulate a List<> . They work on any IEnumerable<> and List<> is one of them, but they return a new sequence with the result. You never use that return value, so your list stays empty.

It's hard to tell what you actually want from a snippet that does not do it, but I think you were looking for this:

var searchMovieList = movieList.Where(m => m.Title.Contains(searckhQuery)).ToList();

if(!searchMovieList.Any())
{
    searchMovieList = movieList;
}

You could just do the following: var searchMovieList = movieList.Where(m => m.Title.Contains(searchQuery).toList()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM