anthonypliu
anthonypliu

Reputation: 12437

How to return linq query into single object

I have this code in my 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 to be able to make this query only return a single result and I can use MyMatches as a MatchesViewModel object so I do not have to use the ToList() feature thus getting rid of the IEnumberable on the view page @model IEnumerable<MatchGaming.Models.MatchesViewModel> so I can turn it into this: @model MatchGaming.Models.MatchesViewModel

Upvotes: 3

Views: 5767

Answers (3)

Cognitronic
Cognitronic

Reputation: 1436

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

Upvotes: 0

Joachim VR
Joachim VR

Reputation: 2340

.Single() will return the one object. If there's more than one, or none, it'll throw an exception.

.First() will just give you the first, only throwing an exception when there are no items.

.FirstOrDefault() is the same as .First(), but giving you NULL when there are no items.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838256

You can call the appropriately named extension method Enumerable.Single().

Here are some other related methods and the differences between them depending on how many elements there are in the collection you are querying:

                     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

Upvotes: 7

Related Questions