我有以下代码,我正在返回与userId相关联的结果,然后我想循环遍历结果并构建一个集合并将其返回给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;
}
但我无法弄清楚它的语法,有人可以帮助我。
答案 0 :(得分:0)
您可以转换列表而无需转到foreach循环。您可以使用Select语句执行此操作。我无法验证这个(因此未经测试的代码),但是如果你这样做它应该可以工作:
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>();
}