如何将查询结果存储到通用列表

时间:2011-07-28 08:44:20

标签: asp.net-mvc

以下代码无法编译。编译器错误是

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

以下是代码。

[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);
}

其中MyTitleObject定义为

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

总之,我想要实现的是将结果列表发送到视图。

1 个答案:

答案 0 :(得分:2)

您只需在选择行上指定类型:

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