2

I have the following code in my controller which gets the first result of a search with multiple words. Similar to the answer to this question: ASP:NET MVC multiple words in search

var items = from s in db.Items select s;

if (!string.IsNullOrEmpty(searchString) && !searchString.Any(x => Char.IsWhiteSpace(x)))
{
    searchString.Trim();
    items = items.Where(s => s.keywords.Contains(searchString) || s.notes.Contains(searchString)

} 
else if (!string.IsNullOrEmpty(searchString) && searchString.Any(x => Char.IsWhiteSpace(x)))
{
    searchString.Trim();
    string[] strings = searchString.Split(' ');
    var finalItems = new List<Items>();

    foreach (var splitString in strings)
    {
        finalItems.Add(items.FirstOrDefault(s => s.notes.Contains(splitString)
            || s.keywords.Contains(splitString));
    }

    items = finalItems.ToList().AsQueryable();

    return View(items.ToPagedList(pageNumber, pageSize));
}

I want to get all the matching results instead of the first match. Now when I try to change the .FirstOrDefault line to:

finalItems.Add(items.Where(s => s.notes.Contains(splitString)
                    || s.keywords.Contains(splitString)

I get a 'cannot convert from 'System.Linq.IQueryable(MyProject.Models.Items)' to 'MyProject.Models.Items.

I've tried changing my items assignment to:

var items = from s in db.Items
                    select s as IQueryable(Items);

That seems to fix the issue but then it breaks all my s.keywords.Contains or s.notes.Contains with the error 'IQueryable(Items) does not contain a definition for keywords or notes and no extension method keywords or notes accepting a first argument of type IQueryable(Items) could be found'.

stuartd
  • 70,509
  • 14
  • 132
  • 163
dlp_dev
  • 190
  • 1
  • 14
  • With `FirstOrDefault()` you get like the Name of the method says 1 item or nothing. When you want to get more than 1 item like you coded with `Where()` you get back a Collection. Now you have to change ALL your methods, that they can handle a Collection of Items instead just only 1 Item – Yggraz Aug 04 '17 at 09:44

1 Answers1

3

FirstOrDefault() returns only one element of some type(MyProject.Models.Items in your case) or null.

Where() returns collection of items.

Add() method expects MyProject.Models.Items - one element, not collection.

You should use AddRange() to add collection:

finalItems.AddRange(items.Where(s => s.notes.Contains(splitString)
                    || s.keywords.Contains(splitString);
Roman
  • 11,966
  • 10
  • 38
  • 47