Ronald
Ronald

Reputation: 1542

How to store query result to a generic list

The code below does not compile. The compiler error is

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<AnimeVoter.Models.MyTitleObject>' d:\dev\mvc\AnimeVoter\AnimeVoter\Controllers\SearchController.cs

Below is the code.

[HttpPost]
public ActionResult Search(FormCollection collection)
{
    string filter = collection["search_fld"];

    List<MyTitleObject> list = 
        (
        from O in db.Titles 
        join K in db.TitleDescriptions on O.Id equals K.TitleId
        where O.Name.ToLower() == filter.ToLower()
        select new { Name = O.Name, Description = K.Description, UrlImage = O.UrlImage, Votes = O.Votes }
        ).ToList(); // this is where the error points at

    return View(list);
}

where MyTitleObject is defined as

public class MyTitleObject
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string UrlImage { get; set; }
    public int Votes { get; set; }
}

In summary what I am trying to achieve is to send the resulting list to the view.

Upvotes: 1

Views: 473

Answers (1)

Richard Dalton
Richard Dalton

Reputation: 35793

You just need to specify the type on the select line:

select new MyTitleObject { Name = O.Name, Description = K.Description, UrlImage = O.UrlImage, Votes = O.Votes }

Upvotes: 2

Related Questions