每次迭代,此查询都会为每个填充的地址创建一个 EmailRecipient。不经过多次迭代可以吗?
var addedRecipients = (from oldRecip in oldEmailRecipients
where !string.IsNullOrWhiteSpace(oldRecip.EmailAddress1)
select new EmailRecipient
{
UserName = oldRecip.UserName,
EmailAddress = oldRecip.EmailAddress1
}
).Union(from oldRecip in oldEmailRecipients
where !string.IsNullOrWhiteSpace(oldRecip.EmailAddress2)
select new EmailRecipient
{
UserName = oldRecip.UserName,
EmailAddress = oldRecip.EmailAddress2
});
最佳答案
您可以使用 SelectMany
扩展方法:
var addedRecipients = oldEmailRecipients.SelectMany(e=>
{
var result= new List<EmailRecipient>();
if(!string.IsNullOrWhiteSpace(e.EmailAddress1))
{
result.Add(new EmailRecipient
{
UserName = e.UserName,
EmailAddress = e.EmailAddress1
});
}
if(!string.IsNullOrWhiteSpace(e.EmailAddress2))
{
result.Add(new EmailRecipient
{
UserName = e.UserName,
EmailAddress = e.EmailAddress2
});
}
return result;
});
更新
我上面展示的解决方案只适用于 Linq to Objects。您的评论表明您正在使用 EF。一个简单的解决方案是在 SelectMany
之前调用 AsEnumerable
方法以切换到 Linq to Objects,但如果您不先过滤收件人,这可能会损害您的性能。
另一种解决方案可能是在调用 SelectMany
之前仅从您的服务器中选择您首先需要的数据,以便在这种情况下不加载您不需要的其他列:
...Where(...)
.Select(r=>new{UserName=r.UserName,
EmailAddress1=r.EmailAddress1,
EmailAddress2=r.EmailAddress2 })
.AsEnumerable()
.SelectMany(...);
关于c# - 使用 Linq 每次迭代选择多个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37441939/