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

时间:2011-03-16 23:08:29

标签: c# asp.net linq 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());
        }

    }

我希望能够使此查询仅返回单个结果,并且我可以将MyMatches用作MatchesViewModel对象,因此我不必使用ToList()功能从而在视图页面上删除IEnumberable @model IEnumerable<MatchGaming.Models.MatchesViewModel>所以我可以将其变为:@model MatchGaming.Models.MatchesViewModel

3 个答案:

答案 0 :(得分:6)

您可以调用适当命名的扩展方法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

答案 1 :(得分:1)

.Single()将返回一个对象。如果有多个,或者没有,那么它会抛出异常。

.First()只会给你第一个,只有在没有项目时才会抛出异常。

.FirstOrDefault()与.First()相同,但在没有项目时给你NULL。

答案 2 :(得分:0)

我通常使用.UniqueResult&lt;&gt;()。它返回单个结果或空引用。