[英]How to avoid redundant List using LINQ
I have a Report object that has Recipients property (of String datatype). 我有一个Report对象,它具有Recipients属性(String数据类型)。 The Recipients property will hold all the recipients' email address in
comma separated string
. “收件人”属性将以
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
? 有没有更好的方法来避免使用
LINQ
冗余的List和Collection?
Report report = new Report();
report.Recipients = "test@test.com, demo@demo.com";
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.
CA1002 :不要公开通用列表。 System.Collections.Generic.List is a generic collection designed for performance not inheritance and, therefore, does not contain any virtual members.
System.Collections.Generic.List是一个通用集合,专为性能而非继承而设计,因此不包含任何虚拟成员。 http://msdn.microsoft.com/en-us/library/ms182142(v=vs.80).aspx
http://msdn.microsoft.com/en-us/library/ms182142(v=vs.80).aspx
You can just use a HashSet
. 你可以使用
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()
Just off the top of my head: 就在我的头顶:
var emailObjectCollection = new Collection<Email>(
new List<string>(report.Recipients.Split(',')).Distinct()
.Select<string, Email>(e =>
{
var email = new Email();
email.EmailAddress = e;
}).ToList());
That should be the LINQ-y way of populating a Collection<T>
with unique values. 这应该是使用唯一值填充
Collection<T>
的LINQ-y方法。 Just curious though, why use a Collection
? 只是好奇,为什么要使用
Collection
? If you need to pass this enumerable around, would it not make more sense to use IEnumerable
? 如果你需要传递这个可枚举的内容,使用
IEnumerable
会不会更有意义吗?
Plus, you could suppress the CA1002
message with a suppression attribute - there are valid exceptions to the rule, from time to time (IMHO). 另外,您可以使用抑制属性来抑制
CA1002
消息 - 规则有时会有有效的例外(IMHO)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.