如何将linq查询返回到单个对象

ant*_*liu 3 c# linq asp.net asp.net-mvc-3

我的控制器中有这个代码:

 public ActionResult Details(int id)
    {
        using (var db = new MatchGamingEntities())
        {
            var MyMatches = from m in db.Matches
                            join n in db.MatchTypes on m.MatchTypeId equals n.MatchTypeId
                            where m.MatchId == id
                            select new MatchesViewModel
                            {
                                MatchType = n.MatchTypeName,
                                MatchId = m.MatchId,
                                MatchName = m.MatchTitle,
                                MatchDescription = m.MatchDescription,
                                Wager = m.Wager
                            };
            ViewBag.MyMatches = MyMatches.ToList();



            return View(MyMatches.ToList());
        }

    }
Run Code Online (Sandbox Code Playgroud)

我希望能够使这个查询只返回一个结果,我可以使用MyMatches作为MatchesViewModel对象,所以我不必使用该ToList()功能,从而摆脱视图页面上的IEnumberable,@model IEnumerable<MatchGaming.Models.MatchesViewModel>所以我可以把它变成这个:@model MatchGaming.Models.MatchesViewModel

Mar*_*ers 7

您可以调用适当命名的扩展方法Enumerable.Single().

以下是一些其他相关方法以及它们之间的差异,具体取决于您要查询的集合中有多少元素:

                     No elements          More than one element
 First               Throws exception     First element returned
 FirstOrDefault      default(T)           First element returned
 Single              Throws exception     Throws exception
 SingleOrDefault     default(T)           Throws exception