简体   繁体   中英

How to pass the value of an Linq Query to a normal String without using List?

A very simple question, yet I couldn't find the answer.

Let's say we have this:

    [HttpPost]
    public ActionResult Comparison(int id)
    {
        string makeLst = new List<String>();

        var makeQry = from m in db.Car
                      where m.ID == id
                      select m.Make;

        makeLst = makeQry.AddRange(makeQry);

        ViewBag.make = new List<String>(makeLst);
        return View();
    }

The "makeQry" Result View would be just one word (String). So I wanted to not use List for this, and just use String. Using ".ToString()" won't work since "makeQry.ToString()" would be the Query itself instead of the it's results. And I checked there is no method such as for instance makeQry.Result or something to get the result of Query.

Thank you.

You can use First() or FirstOrDefault() to get the single result:

ViewBag.make = makeQry.FirstOrDefault();

(The difference is that First throws an exception if the collection is empty, whereas FirstOrDefault just returns a null value in that case.)

Details: If you know for sure there will always be a matching value for ID then the below should do the job (not tested)

[HttpPost]
public ActionResult Comparison(int id)
{
   ViewBag.make = db.Car.FirstOrDefault(x => x.ID == id).Make;

   return View();
}

or if you prefer to keep the linq syntax how you are doing it

[HttpPost]
public ActionResult Comparison(int id)
{
   ViewBag.make = (from m in db.Car
                   where m.ID == id
                   select m.Make).FirstOrDefault();

   return View();
}
[HttpPost]
public ActionResult Comparison(int id)
{
    var makeQry = from m in db.Car
                  where m.ID == id
                  select m.Make;
    //As soon as the result is guaranteed to contain only one object 
    ViewBag.make = makeQry.SingleOrDefault();
    return View();
}

It uses Enumerable.SingleOrDefault Method (IEnumerable) , which returns the single element of the input sequence or null if there are no elements. It'll throw an exception, if the sequence contains more than one element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM