【问题标题】:how to send an email for either the first and second or the last and pre last element of array如何为数组的第一个和第二个或最后一个和最后一个元素发送电子邮件
【发布时间】:2019-02-17 18:19:34
【问题描述】:

我有一组电子邮件地址。我可以使用 foreach(如下)发送所有电子邮件。 如何仅针对给定数组中的第一个和第二个元素或最后一个和最后一个元素发送电子邮件?

string[] emails = storeEmails.Split(new char[] { ';' });

foreach (string emailTo in emails)
{
    emailTemplate.Email = emailTo;
    _eventService.SendEmail(emailTemplate, emailBody);
} 

【问题讨论】:

  • 使用数组索引而不是 foreach 循环

标签: c# arrays for-loop


【解决方案1】:

您可以使用Linq 轻松做到这一点。

这是一个采用前两个的示例(使用xUnit 演示):

using System.Linq;
using Xunit;

namespace Q54736241
{
    public class Example
    {
        [Fact]
        public void Example1()
        {
            var strings = new[] { "one", "two", "three", "four", "five" };

            var firstTwo = strings.Take(2);

            Assert.Equal(new[] {"one", "two"}, firstTwo);
        }
    }
}

您需要做更多的工作才能获得最后两个。查看此相关问题以获取一些示例:Using Linq to get the last N elements of a collection?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2017-02-27
    • 2011-06-06
    • 2013-12-01
    • 1970-01-01
    • 2016-02-22
    • 2012-06-11
    相关资源
    最近更新 更多