简体   繁体   English

如何在不使用 List 的情况下将 Linq 查询的值传递给普通字符串?

[英]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). “makeQry”结果视图只是一个词(字符串)。 So I wanted to not use List for this, and just use String.所以我不想为此使用 List,而只使用 String。 Using ".ToString()" won't work since "makeQry.ToString()" would be the Query itself instead of the it's results.使用“.ToString()”将不起作用,因为“makeQry.ToString()”将是查询本身而不是它的结果。 And I checked there is no method such as for instance makeQry.Result or something to get the result of Query.我检查了没有诸如 makeQry.Result 之类的方法来获取查询的结果。

Thank you.谢谢你。

You can use First() or FirstOrDefault() to get the single result:您可以使用First()FirstOrDefault()来获得单个结果:

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.) (不同之处在于,如果集合为空,则First抛出异常,而FirstOrDefault在这种情况下仅返回空值。)

Details: If you know for sure there will always be a matching value for ID then the below should do the job (not tested)详细信息:如果您确定总是有一个匹配的 ID 值,那么下面应该可以完成这项工作(未测试)

[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或者如果你更喜欢保持 linq 语法你是如何做的

[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.它使用Enumerable.SingleOrDefault 方法 (IEnumerable) ,如果没有元素,则返回输入序列的单个元素或 null。 It'll throw an exception, if the sequence contains more than one element.如果序列包含多个元素,它将抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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