Linq FirstOrDefault

前端 未结 4 1818
醉话见心
醉话见心 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
    }
    
    0 讨论(0)
  • 2020-12-06 12:46

    If you want to count the records, count the result of the query without FirstOrDefault.

    var mngr = (from tr in DataContext.Manager
                    where tr.ID = "2323")
    if(mngr.Count() == 0)
       ....
    else
       Manager manager = mngr.First(); //No need for default since we know we have a record.
    

    You can still run first or default on the mngr to get the specific manager.

    0 讨论(0)
  • 2020-12-06 13:00

    You are using an ID for the where condition, I think you should've already guaranteed that this query returns only one result.

    If your problem is having no result please check the usage of FirstOrDefault() from MSDN title.

                int[] numbers = { };
                int first = numbers.FirstOrDefault();
                Console.WriteLine(first);
    
                /*
                 This code produces the following output:
    
                 0
                */
    
    0 讨论(0)
  • 2020-12-06 13:00

    You can use the SingleOrDefault extension method to express that the query only ever should return one result.

    Manager manager = (from tr in DataContext.Manager 
                       where tr.ID = "2323").SingleOrDefault();
    

    However it does not tell you whether you got 0 results or more than 1.

    0 讨论(0)
提交回复
热议问题