How to return linq request in one object

I have this code in the controller:

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

    }

I want this query to return only one result, and I can use MyMatches as a MatchesViewModel object, so I do not need to use the function ToList(), thereby getting rid of IEnumberable on the view page @model IEnumerable<MatchGaming.Models.MatchesViewModel>so I can include it in this:@model MatchGaming.Models.MatchesViewModel

+3
source share
3 answers

You can call a method with a name extension Enumerable.Single().

Here are some other related methods and the differences between them depending on the number of elements in the request:

                     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
+6

.Single() . , .

.First() , , .

.FirstOrDefault() .First(), NULL, .

+1

I usually use .UniqueResult <> (). It returns a single result or null reference.

0
source

All Articles