我試圖將多個字符串添加到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