简体   繁体   English

如何重写开关语句

[英]How to rewrite switch-statement

Is there a syntactic sugar or more elegant way to refactor the following code: 是否有语法糖或更优雅的方法来重构以下代码:

foreach (var recipient in subscription.Recipients)
{
    switch (recipient.ReceivingMethod)
    {
        case ReceivingMethod.To:
            mail.To.Add(recipient.EMailAdress);
            break;
        case ReceivingMethod.Copy:
            mail.Copy.Add(recipient.EMailAdress);
            break;
        case ReceivingMethod.BlindCopy:
            mail.BlindCopy.Add(recipient.EMailAdress);
            break;
    }
}

423 characters 423个字符

foreach (var recipient in subscription.Recipients)
{
    switch (recipient.ReceivingMethod)
    {
        case ReceivingMethod.To:
            mail.To.Add(recipient.EMailAdress);
            break;
        case ReceivingMethod.Copy:
            mail.Copy.Add(recipient.EMailAdress);
            break;
        case ReceivingMethod.BlindCopy:
            mail.BlindCopy.Add(recipient.EMailAdress);
            break;
    }
}

311 characters 311个字符

mail.To.AddRange(subscription.Recipients.Where(c => c.ReceivingMethod == ReceivingMethod.To))
mail.Copy.AddRange(subscription.Recipients.Where(c => c.ReceivingMethod == ReceivingMethod.Copy))
mail.BlindCopy.AddRange(subscription.Recipients.Where(c => c.ReceivingMethod == ReceivingMethod.BlindCopy))

Either way. 无论哪种方式。 Though i personally think the former is the more readable for me 虽然我个人认为前者对我来说更具可读性

Though if you have printable character OCD, maybe the later 虽然如果您有可打印字符OCD,也许以后

Note : I'm not sure a Dictionary brings much to the table though 注意 :我不确定Dictionary会带来很多好处


Update from Comments 评论更新

Zohar Peled : That's also assuming mail.To , mail.Copy and mail.BlindCopy supports AddRange - I'm not sure that assumption is correct, since System.Net.MailMessage use the MailAddressCollection classes for To, CC and BCC, and that class does not support AddRange Zohar Peled :这也假设mail.Tomail.Copymail.BlindCopy支持AddRange我不确定这个假设是正确的,因为System.Net.MailMessage对To,CC和BCC使用MailAddressCollection类,并且该类不支持AddRange

and

GolezTrol : Also note that the second option is not just syntactical sugar. GolezTrol :还请注意,第二个选项不仅是语法糖。 Internally you loop through the recipients 3 times, and each results in an enumerable that is passed to AddRange , instead of one by one to Add. 在内部,您遍历接收者3次,每次都会导致将一个可枚举的对象传递给AddRange ,而不是一个一个地传递给Add。 If AddRange is supported, the end result should be the same, though, so it's typically not something to worry about 如果支持AddRange ,则最终结果应该相同,因此通常不必担心

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

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