简体   繁体   English

将foreach语句重构为LINQ

[英]Refactor foreach statement to LINQ

I have been working on a project and I'm actually refactoring some code. 我一直在从事一个项目,实际上是在重构一些代码。 I have encountered myself with lots of foreach and if statements, which could be easily replace with LINQ. 我遇到了很多foreach和if语句,这些语句可以很容易地用LINQ替换。

But I have this code snippet, that I wonder how I could make it more functional style. 但是我有这个代码片段,我想知道如何使它更具功能性。

foreach (var notification in notifications)
{
    if (_emailService.SendEmail(notification.Message.Subject, notification.Message.Body, notification.Message.MailTo))
    {
        successNotificationIDs.AddRange(notification.ID);
    }
    else
    {
        errorCount++;
    }
}

The SendEmail method of the EmailService returns a bool. EmailService的SendEmail方法返回布尔值。 If its execution has been successfully, it will add an IEnumerable of Int to a declared collection (successNotificationsIDs). 如果执行成功,它将向声明的集合(successNotificationsIDs)中添加一个IEnumerable of Int。 If not, I will increase the errorCount variable. 如果没有,我将增加errorCount变量。

To separate the items of a sequence into all of those that pass some predicate and those that didn't, you can use ToLookup . 要将序列中的项目分为通过某些谓词的所有项和未通过谓词的所有项,可以使用ToLookup Use your predicate as the selector: 使用谓词作为选择器:

var lookup =  notifications.ToLookup(notification =>
    _emailService.SendEmail(notification.Message.Subject, 
        notification.Message.Body,
        notification.Message.MailTo));

var successfulIDs = lookup[true].SelectMany(notification => notification.ID);
var errorCount = lookup[false].Count();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM