Baldie47
Baldie47

Reputation: 1274

Assign properties of one IEnumerable to another

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 ?

Upvotes: 0

Views: 50

Answers (1)

Javlon Fattoev
Javlon Fattoev

Reputation: 26

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

Upvotes: 1

Related Questions