我试图将多个字符串添加到C#中的MailAddress。ForEach和foreach
如果我用ForEach
,我的代码看起来像
foreach (var item in GetPeopleList())
{
m.Bcc.Add(new MailAddress(item.EmailAddress));
}
现在我想用我的foreach(即List.ForEach()
)做到这一点,我不能。
public class Person
{
public Person(string firstName, string lastName, string emailAddress)
{
FirstName = firstName;
LastName = lastName;
EmailAddress = emailAddress;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
static void Main(string[] args)
{
MailMessage m = new MailMessage();
List<Person> people = GetPeopleList();
m.Bcc.Add(people.ForEach(Person people =>
{
//what goes here?
}
));
}
private static List<Person> GetPeopleList()
{
List<Person> peopleList = new List<Person>();
//add each person, of type Person, to the list and instantiate the class (with the use of 'new')
peopleList.Add(new Person("Joe", "Bloggs", "[email protected]"));
peopleList.Add(new Person("John", "Smith", "[email protected]"));
peopleList.Add(new Person("Ann", "Other", "[email protected]"));
return peopleList;
}
我已经尝试了几个版本/变种这个,但我显然做错了什么。我读了Eric Lippert's page,可惜这也没有帮助。
什么不起作用? – Woot4Moo 2013-02-25 14:03:47
你的问题是错误的方式。你写过:“如果我使用ForEach”,然后使用'foreach' ... – 2013-02-25 14:03:50
我希望你不是这样做,而不仅仅是学习练习。 'List.ForEach()'不应该像你试图使用它的方式那样使用,你已经拥有的版本更清晰。 – JLRishe 2013-02-25 14:08:28