-1

I have an array of email addresses. I can send all email by using foreach(below). How can i send email only for either the first and second or the last and pre last element in given array?

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

foreach (string emailTo in emails)
{
    emailTemplate.Email = emailTo;
    _eventService.SendEmail(emailTemplate, emailBody);
} 
Dale K
  • 25,246
  • 15
  • 42
  • 71

1 Answers1

0

You can do that easily with Linq.

Here's an example (demonstrated using xUnit) of taking the first two:

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);
        }
    }
}

You'll need to do a bit more work to get the last two. Check out this related question for some examples: Using Linq to get the last N elements of a collection?

xander
  • 1,689
  • 10
  • 18