简体   繁体   English

为C#中的每个表达式向lambda添加一个条件

[英]add a condition to the lambda for each expression in C#

Basically I want to do this 基本上我想这样做

foreach (var TA in TheToAddresses)
{
    if(TA.ToLower () != "a@a.com")
    {
        _message.ToRecipients.Add(TA);
    }
}

how do I modify this line to include the condition as well? 如何修改此行以同时包含条件? Thanks 谢谢

TheToAddresses.ForEach(TA => _message.ToRecipients.Add(TA));
TheToAddresses.ForEach(TA => 
{
  if(TA.ToLower () != "a@a.com")
     _message.ToRecipients.Add(TA) 
});

If ToRecipients is of type List you can write: 如果ToRecipientsList类型,则可以编写:

_message.ToRecipients.AddRange(TheToAddresses.Where(TA => TA.ToLower() != "a@a.com"));

You can write a multi-line lambda method by wrapping it with { }: 您可以使用{}包装多行lambda方法:

TheToAddresses.ForEach(TA =>
    {
        if(TA.ToLower () != "a@a.com")
        {
             _message.ToRecipients.Add(TA);
        }
     });
TheToAddresses.Where(r=> r.ToLower () != "a@a.com").ToList()
.ForEach(TA => _message.ToRecipients.Add(TA));
TheToAddresses.Where(address => address.ToLower() != "a@a.com").ToList().ForEach(TA => _message.ToRecipients.Add(TA));
TheToAddresses.Where(ta => ta.ToLower() != "a@a.com")
              .ForEach(TA => _message.ToRecipients.Add(TA));

What you wrote is nearly the right way. 您写的几乎是正确的方法。 LINQ shouldn't have side-effects. LINQ不应该有副作用。 See http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx 参见http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx

foreach (var TA in TheToAddresses)
{
    if(!StringComparer.OrdinalIgnoreCase.Equals(TA, "a@a.com"))
    {
        _message.ToRecipients.Add(TA);
    }
}

The only point is that if you want to do case insensitive comparisons you don't ToLower() / ToUpper() (see http://blog.codinghorror.com/whats-wrong-with-turkey/ , beginning with Strings are where it really starts to get hairy ) 唯一的一点是,如果要进行不区分大小写的比较,则不要ToLower() / ToUpper() (请参阅http://blog.codinghorror.com/whats-wrong-with-turkey/ ,从字符串开始的地方它真的开始变得毛茸茸的

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

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