Assign properties of one IEnumerable to another

Viewed 41

I have a class Person:

public class Person
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string LastName { get; set; }

        public string Email { get; set; }
    }

and a class Email:

public class Email
{
    public int Id { get; set; }

    public string EmailAddress { get; set; }
}

and I have IEnumerables of both:

public IEnumerable<Person> Persons;

public IEnumerable<Email> Emails;

I want to to a process to assign all emails to the persons, based on equal Id.

I was trying something like

foreach (var person in Persons.Where(p => p.Id.Equals(Emails.Select(x=>x.Id))))
    {
        person.Email = Emails.Select(e => e.EmailAddress);
    }

but this is where I'm struggling a bit, the working versions I saw are using 2 foreach, which I understand is not performing. what could be the approach to assign 1 email to each person where Persons.Id == Emails.Id ?

1 Answers
foreach(var person in Persons)
  {
     var email = Emails.FirstOrDefault(email => email.Id == person.Id);
     if(email != null)
       person.Email = email.Email;
  }
Related