Nate Pet
Nate Pet

Reputation: 46222

Linq FirstOrDefault

I have the following LINQ query:

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

How can I check if the query did return 1 record as I cannot do .Count to get the count.

Upvotes: 8

Views: 36061

Answers (4)

Jeff Mercado
Jeff Mercado

Reputation: 134821

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
}

Upvotes: 15

ChrisWue
ChrisWue

Reputation: 19020

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.

Upvotes: 0

Bastardo
Bastardo

Reputation: 4152

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
            */

Upvotes: 0

Godeke
Godeke

Reputation: 16281

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.

Upvotes: 0

Related Questions