使用foreach for C#在Asp.NetCore Web API中发送电子邮件

bq9c1y66  于 2023-02-20  发布在  .NET
关注(0)|答案(2)|浏览(115)

我有两个不同的IEnumerable<>:一个用于从Gmail收件箱获取ID,另一个用于获取MailMessage列表,如下面的代码所示。

client.DefaultMailbox = "INBOX";
          IEnumerable<uint> sids = client.Search(SearchCondition.Unseen());
          IEnumerable<MailMessage> AllMessage = client.GetMessages(sids);
          List<LiteInbox> allmail = new List<LiteInbox>();

我想使用两个foreach循环来获取来自Gmail收件箱的每个MailMessage的特定ID,如果我在foreach中迭代foreach,它将获取每个MailMessage的ID。

foreach (uint ids in sids)
  {
      id = ids;
      LiteInbox lite=new LiteInbox();

      foreach(var mail in AllMessage )
      {
         lite.id=id;
         lite.sender=mail.sender;
         lite.subject=mail.subject;
      }

   }

对于收件箱中的每一封邮件,一次一封地循环两个foreach语句,如果有四封未读邮件,则分别循环并为每一封分配一个ID。

{   [
   {
    id: 1,
    subject: welcome,
    body:hbjdbjddjh,
    sender: wealsegun@gmail.com     },
{
    id: 1,
    subject: welcome,
    body:hbjdbjddjh,
    sender: wealsegun@gmail.com      },
{
    id: 1,
    subject: welcome,
    body:hbjdbjddjh,
    sender: wealsegun@gmail.com      },
{
    id: 1,
    subject: welcome,
    body:hbjdbjddjh,
    sender: wealsegun@gmail.com      },
],
   [
   {
    id: 2,
    subject: welcome,
    body:hbjdbjddjh,
    sender: wealsegun@gmail.com      },
{
    id: 2,
    subject: welcome,
    body:hbjdbjddjh,
    sender: wealsegun@gmail.com      },
{
    id: 2,
    subject: welcome,
    body:hbjdbjddjh,
    sender: wealsegun@gmail.com      },
{
    id: 2,
    subject: welcome,
    body:hbjdbjddjh,
    sender: wealsegun@gmail.com     },
]}

我怎样才能做到这一点?

0h4hbjxa

0h4hbjxa1#

假设AllMessagesids的顺序相同,并且这些列表中的元素数量相等(否则我不知道如何为消息分配正确的id),您可以执行以下操作

for (int i = 0; i < AllMessage.Count; i++) {
    LiteInbox lite=new LiteInbox();
    lite.id = sids[i];
    lite.sender=AllMessage[i].sender;
    lite.subject=AllMessage[i].subject;
    allmail.Add(lite);    
}

或者使用foreach

int i = 0;  //you'll need that index to access the corresponding element in the other list
foreach (int id in sids) {
    LiteInbox lite=new LiteInbox();
    lite.id = id;
    lite.sender=AllMessage[i].sender;
    lite.subject=AllMessage[i].subject;
    allmail.Add(lite);            
    i++;
}
hs1ihplo

hs1ihplo2#

如果类MailMessage具有sid属性(我怀疑,MailMessage类是.Net framework类吗?),您需要检索与每个Email关联的每个sid,您需要修改SearchGetMessages之一或两者的签名,以便它返回类似于

List<Pair<uint, MailMessage>>

其中列表的每个元素都是消息及其ID
在那之后,你就不需要双前脸了

相关问题