gpt4 book ai didi

c# - ForEach 和 foreach

转载 作者:太空宇宙 更新时间:2023-11-03 21:49:55 30 4
gpt4 key购买 nike

我正在尝试将多个字符串添加到 C# 中的 MailAddress。

如果我使用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", "Joe.Bloggs@foo.bar"));
peopleList.Add(new Person("John", "Smith", "John.Smith@foo.bar"));
peopleList.Add(new Person("Ann", "Other", "Ann.Other@foo.bar"));
return peopleList;
}

我已经尝试了几个版本/变体,但我显然做错了什么。我读了Eric Lippert's page关于它,遗憾的是这也没有帮助。

最佳答案

你需要这样的东西

people.ForEach(Person p => {
m.Bcc.Add(new MailAddress(p.EmailAddress));
});

不是添加使用 ForEach 选择的单个项目范围,而是在列表中添加单个项目 ForEach person。

也就是说...我自己更喜欢常规的 foreach 循环。

关于c# - ForEach 和 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15068742/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com