Canvas
Canvas

Reputation: 5897

MVC search a LINQ query

I have a very simple query

var query = (from s in db.Stocks
             select s).ToList();

and now basically I want to then search that query to see if any of the stock objects names in the query contain "a"

I have this

if(!string.IsNullOrEmpty(searchModel.Name) )
{
    query = query.Where(x => x.Name.Contains(searchModel.Name));
}

but I am getting this error

Cannot implicity convert type "system.collections.generic.ienumerable<etc etc> to system.collections.generic.list

How can I search my query result?

Its ok I have the answer I just need to add .ToList to the end of my query statement like so

if(!string.IsNullOrEmpty(searchModel.Name) )
{
    query = query.Where(x => x.Name.Contains(searchModel.Name)).ToList();
}

Upvotes: 0

Views: 1175

Answers (3)

khaled saleh
khaled saleh

Reputation: 518

you can re-write the query as following:

var query = (from s in db.Stocks.ToList()
             where !string.IsNullOrEmpty(searchModel.Name) ? s.Contains(searchModel.Name) : true
             select s).ToList(); 

the new added line means: if SearchModel.Name is filled then search using it, otherwise do nothing

or you can keep your code as it, but add .ToList() after the table name, or remote .ToList() on the end of your query code which enforce the datatype of result

Upvotes: 0

Dan Hunex
Dan Hunex

Reputation: 5318

The reason is because in the first query

  var query = (from s in db.Stocks
             select s).ToList();

you have fixed the data type of the variable query to be List (toList()) . Now when you query it again with Where it returns IEnumerable and can't be assigned to the type List . You can do it in one line as in below

 var query = from s in db.Stocks
              where s.contains(searchModel.Name)
              select s

Upvotes: 1

Jonesopolis
Jonesopolis

Reputation: 25370

try

query = query.Where(x => x.Name.Contains(searchModel.Name)).ToList();

Upvotes: 0

Related Questions