I am quite new to MVC from webforms and it has been a really, really steep learning curve for me. Here is the function in the tutorial that I am following:
public ActionResult Index(string id)
{
string searchString = id;
var movies = from m in db.Movies
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return View(movies);
}
Here is what I think I know that is happening. The method being an Action result(without parameters) re returning a view. The parameters are added to tell the application to look for a "id" string.
I find the lambda statement a little easier to understand. The if
is checking to see if the searchString
is null if not it returns the movie that matches the description in searchString
.
In the method however, searchString
is given the value of id
in the parameter. Here is where I start getting lost, right after searchString
is defined, a LINQ statement is placed inside the variable movies
. In that statement, what is the purpose of m
? Why is it not defined or is it? The same with the s
in the lambda.
Both m
and s
are implicitly typed. Since you are selecting m
from movies
, you don't need to tell LINQ what m
is. It can imply the type by looking at what db.Movies
is a collection of. So if db.Movies
was IEnumerable<Movie>
(for example) then m
would be a Movie
.
There is nothing to stop you from specifying the type if you really want to, so you could type:
var movies = from Movie m in db.Movies
select m;
But you rarely need to.
Note you are also implicitly typing movies
, it's the same concept. So long as the compiler can unambiguously figure out what the type should be.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments