Populate list from linq query result

c# dapper linq list

Question

I have the following code, I'm returning results that are associated with the userId, I then want to loop through the results and build a collection and return it back to the UI.

 public List<UserEmails> LoadUsersInbox(Int64 userId, int status)
    {
        List<UserEmails> userEmails = null;

        using (var sqlCon = new SqlConnection(Context.ReturnDatabaseConnection()))
        {
            var emails = sqlCon.Query<UserEmailEntity>(@"SELECT e.EmailId, e.ItemId, u.Username as FromUserName, e.EmailReceived
                                                   FROM User_Emails e
                                                   INNER JOIN User_Profile u on e.FromUserId = u.UserId
                                                   WHERE ToUserId = @userId and EmailStatus = @Status",
                                                   new { ToUserId = userId, Status = status }).OrderBy(d => d.EmailReceived);

            foreach (var item in emails)
            {
                // loop through and build and List of UserEmails
            }
        }

        return userEmails;
    }

But I can't figure out the syntax for it, can some one help me please.

Popular Answer

You can transform the list without going to the foreach loop. You do this with the Select statement. I am not able to verify this (thus untested code), but it ought to work if you make do this:

public List<Int64> LoadUsersInbox(Int64 userId, int status)
{
    using (var sqlCon = new SqlConnection(Context.ReturnDatabaseConnection()))
    {
       return sqlCon.Query<UserEmailEntity>
            (@"SELECT e.EmailId, e.ItemId, u.Username as FromUserName, e.EmailReceived
               FROM User_Emails e
               INNER JOIN User_Profile u on e.FromUserId = u.UserId
               WHERE ToUserId = @userId and EmailStatus = @Status",
               new { ToUserId = userId, Status = status })
            .OrderBy(d => d.EmailReceived)
            .Select(usrEmlEnt => usrEmlEnt.EmailId);
    }
    return new List<Int64>();
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why