BillyGisbourne BillyGisbourne - 1 month ago 14
C# Question

(C# LINQ) Select firstname and lastname using email

I'm very new to LINQ and SQL queries and I have searched the internet for about 2 hours now trying to find the answer to my question, that's why I'm posting here.

I'm trying to grab a User's firstname and lastname in a LINQ query by using the User's Email address which I know the value of.

An example is:

using (userEntities db = new userEntities())
{
var query = from o db.Users
where o.email == userEmail
select o;

if (query.SingleOrDefault() != null)
{
...
}
}


This only selects the email address, how do I then go about using that row and getting the firstname and lastname?

Thank you in advanced.

Answer

query.SingleOrDefault() will return the row if it exists. Assign it to a variable and use after a null check to get the required information.

var query = from o db.Users
            where o.email == userEmail
            select o;

var result = query.SingleOrDefault();
if (result != null)
{
      ... // result.UserName, etc.
}