简体   繁体   中英

(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.

You have a db Object, that has a sequence called Users where each element in the sequence is a User that has a property with the name email.

Apparently every user also has two other properties: firstName and lastName.

In linq, whenever you have a sequence of "thingies" and you want only "thingies" that match a certain predicate you use the function Where, exactly like you did.

If you have a sequence of "thingies" and for every "thingie" you want to create one "other thingy" based on the original "thingie" you use the function Select. Converting one input element into one output element is called Projection in Linq. With the function Select you project (convert) every element of your input sequence into exactly one element of the output sequence

So if you want to create an "other thingie" with the firstName and the lastName of you thingies, you do as follows:

class UserName
{
    public string firstName {get; set;}
    public string lastName {get; set;
}
var result = db.Users
    .Where(user => user.email == useremail)
    .Select(user => new UserName()
    {
        FirstName = user.FirstName,
        LastName = user.LastName,
    });

I take every user that matched the userEmail and create a new object of class UserName that contains the FirstName and the LastName of every user.

The method used above means that for every projection you want to use in a Select statement you'll have to define a class. This is quite a nuisance, especially if you are only going to use the result of the statement in a very limited space, for instance only within the procedure where you created your new object.

If you don't have to pass your query result to other functions and only need it within this function (more precisely: don't need a formal parameter) you don't have to declare the class UserName. You can use an anonymous type. Anonymous types make it possible to do the select without having to define the type you are projecting to:

var matchingUserNames = db.Users
    .Where(user => user.email == useremail)
    .Select(user => new
    {
        FirstName = user.FirstName,
        LastName = user.LastName,
    });
foreach (var matchingUserName in matchingUserNames)
{
    Console.WriteLine(matchingUserName.FirstName + ' ' 
        + matchingUserName.LastName);
}

Note that I have left out the name of the class. So you can't pass the result to something that has a type name. In fact the only thing you now about the result that it is a sequence of objects where each object has two properties: FirstName and LastName. FirstName has the same type as user.FirstName; LastName has the same type as use.LastName

For anonymous types see the joy of anonymous types

Another article that helped me to get me understand linq was The standard Linq operators

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.
}

Think of query as a question to the database that when enumerated, executes the query and gives you back a collection of User s that comply with your search criteria.

When you do query.FirstOrDefault() you are enumerating the query asking for the first user that meets your conditions if any.

So, answering your question, you can do:

User user = query.FirstOrDefault();

if (user != null)
{
    var name = user.FirstName + " " + user.LastName;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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