加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:42:06 所属栏目:百科 来源:网络整理
导读:我的控制器中有这个代码: 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
我的控制器中有这个代码:

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读