Skip to main content
 首页 » 编程设计

c#之ForEach 和 foreach

2024年02月20日1198°冷暖

我正在尝试将多个字符串添加到 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 循环。