Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid redundant List using LINQ

Tags:

c#

linq

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:

  1. Better code for avoiding one dictionary - Case Sensitivity Issue
  2. Remove duplicates in the list using linq
  3. Using LINQ to find duplicates across multiple properties
  4. C#: Difference between List<T> and Collection<T> (CA1002, Do not expose generic lists)

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

like image 219
LCJ Avatar asked Nov 29 '12 14:11

LCJ


2 Answers

You can just use a HashSet.

var emailObjectCollection = new HashSet<Email>(
     report.Recipients.Split(',').Select(e => new Email() { EmailAddress = e }));
like image 187
Daniel A. White Avatar answered Sep 30 '22 00:09

Daniel A. White


var  emailObjectCollection =   report.Recipients.Split(',')
                                    .Select(m=>new Email(){EmailAddress = m})
                                    .ToList()
like image 30
L.B Avatar answered Sep 30 '22 00:09

L.B