freshr
freshr

Reputation: 985

Can I use a collection initializer with LINQ to return a fully populated collection?

I would like to rewrite the following code in one line, using LINQ. Is it possible?

var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

Upvotes: 7

Views: 2922

Answers (5)

Jodrell
Jodrell

Reputation: 35716

There is a 1 line alternative that doesn't use linq which I provide for completeness. Personally I couldn't recommend it due to the unnecessary string manipulation.

It does however provide a terse solution.

var to = new MailAddressCollection() { string.join(",", recipients) };

Upvotes: 3

Grozz
Grozz

Reputation: 8425

MailAddressCollection doesn't have a constructor that takes list of recipients. If you really want to do it in one line, you can write the following:

    var to = recipients.Aggregate(new MailAddressCollection(), 
        (c, r) => { c.Add(new MailAddress(r)); return c; });

Upvotes: 5

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262989

A LINQ expression would return an IEnumerable<MailAddress>, which cannot be directly converted into a MailAddressCollection.

An alternative would be to Join() the addresses and pass the result to MailAddressCollection's Add() method:

var to = new MailAddressCollection();
to.Add(String.Join(",", recipients));

Upvotes: 1

Stefan
Stefan

Reputation: 14880

You could write an extension method on IEnumerable<MailAddress> which returns a MailAddressCollection:

public static MailAddressCollection ToAddressCollection(this IEnumerable<MailAddress> source)
{
  var to = new MailAddressCollection();
  foreach(string r in source)
  {
    to.Add(new MailAddress(r));
  }
  return to;
}

Then use it like this:

var to = recipients.Select(r => new MailAddress(r)).ToAddressCollection();

Upvotes: 1

ColinE
ColinE

Reputation: 70142

How about this ...

var to = new MailAddressCollection(recipients.Select(r => new MailAddress(r));

Although, this relies on the presence of a constructor on MailAddressCollection (or its superclass) that takes a IEnumerable<MailAddress> as an argument. If it is a subclass of List<T> this will be the case.

Upvotes: -1

Related Questions