I have a Report object that has Recipients property (of String datatype). The Recipients property will hold all the recipients’ email address in comma separated string
. I need to create a “Collection” of Email objects from the comma separated string. I have the following code that uses a List of string to get the email address first. Then I create a collection of email objects.
Is there a better way to avoid the redundant List and Collection using LINQ
?
Report report = new Report();
report.Recipients = "[email protected], [email protected]";
List<string> emailAddressList = new List<string>( report.Recipients.Split(',') );
Collection<Email> emailObjectCollection = new Collection<Email>();
foreach (string emailAddress in emailAddressList)
{
Email email = new Email();
email.EmailAddress = emailAddress;
emailObjectCollection.Add(email);
}
References:
CA1002: Do not expose generic lists. System.Collections.Generic.List is a generic collection designed for performance not inheritance and, therefore, does not contain any virtual members. http://msdn.microsoft.com/en-us/library/ms182142(v=vs.80).aspx
You can just use a HashSet
.
var emailObjectCollection = new HashSet<Email>(
report.Recipients.Split(',').Select(e => new Email() { EmailAddress = e }));
var emailObjectCollection = report.Recipients.Split(',')
.Select(m=>new Email(){EmailAddress = m})
.ToList()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With