ForEach and foreach

本文关键字:foreach and ForEach | 更新日期: 2023-09-27 18:01:04

我试图在C#中向一个MailAddress添加多个字符串。

如果我使用ForEach,我的代码将看起来像

        foreach (var item in GetPeopleList())
        {
            m.Bcc.Add(new MailAddress(item.EmailAddress));
        }

我现在正试着用我的前臂(即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;
        }

我已经尝试了几种版本/变体,但我显然做错了什么。我读了埃里克·利珀特关于这件事的一页,遗憾的是,这也无济于事。

ForEach and foreach

您需要类似的东西

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

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

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

博客直接引用:

第二个原因是这样做不会增加新的代表性语言的力量。这样做可以让你完美地重写清除代码:

foreach(Foo中的Foo({涉及Foo的语句;}

转换为此代码:

foos。ForEach((Foo-Foo(=>{涉及Foo的语句;}(;

它使用几乎完全相同的字符,但略有不同顺序然而,第二个版本更难理解,更难理解调试,并引入闭包语义,从而可能发生更改对象以微妙的方式生存。

埃里克·利珀特明确呼吁不要这样做。

尝试

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

我不知道我是否理解正确,但请尝试:

foreach (var item in GetPeopleList())
{
    m.Bcc.Add(item.EmailAddress));
}

您在代码中创建了一个新的电子邮件地址,但这是不需要的,因为您已经从item获得了一个电子邮件地址。

Linq聚合可以提供一个很好的解决方案。

        MailMessage m = new MailMessage();
        GetPeopleList().Aggregate((result, iter) =>
            {
                m.Bcc.Add(new MailAddress(iter.EmailAddress));
                return result;
            });