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.
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; });
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) };
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));
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();
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.