Linq FirstOrDefault

前端 未结 4 1817
醉话见心
醉话见心 2020-12-06 12:16

I have the following LINQ query:

    Manager mngr = (from tr in DataContext.Manager
                    where tr.Name = \"Jones\").FirstOrDefault();
<         


        
4条回答
  •  無奈伤痛
    2020-12-06 12:34

    First of all, that is not a valid query. When you use the query syntax (from blah in blah ...), you must have a select clause. It should be more like:

    var manager =
        (from n in DataContext.Manager
        where n.Name == "Jones"
        select n).FirstOrDefault();
    

    To answer your question, calling FirstOrDefault() on your query will return the first result of the query or the default value for the type (most likely null in this case). For what you're going for, this won't be an adequate use since the query may contain more than one result.

    If you wish to verify that the query only returns a single result, you should use the SingleOrDefault() method instead. It will return either the one item produced by the query, the default value null if it was empty or throw an exception if there was more than one item.

    If you don't want to throw an exception, it may be easier to just throw the first two results into a list and verify that you only have one.

    var managers =
        (from m in DataContext.Manager
        where m.Name == "Jones"
        select m).Take(2).ToList();
    if (managers.Count == 1)
    {
        // success!
        var manager = managers.First();
        // do something with manager
    }
    else
    {
        // error
    }
    

提交回复
热议问题