Merge lists into one

后端 未结 4 523
我寻月下人不归
我寻月下人不归 2021-01-28 10:57

I saw posts like below which are really hard for me to understand. So I am re-posting it. Sorry if someone feels it\'s duplicate. I have just simple requirements

C# Join

4条回答
  •  孤独总比滥情好
    2021-01-28 11:27

    I'm slightly confused by what your methods are returning, if you need to combine the two results to get full Person objects then there are two ways you might be able to get things working.

    1. If you can rely on the same number of objects being returned in the same order, you can try:

      names.Zip(mailingAddresses, (n, m) => new Person
      {
          Id = n.Id,
          Name = n.Name,
          MailingAddress = m.MailingAddress
      });
      
    2. If you can't rely on both of those conditions, you can use a Join:

      names.Join(mailingAddresses, n => n.Id, m => m.Id, (n, m) => new Person
      {
          Id = n.Id,
          Name = n.Name,
          MailingAddress = m.MailingAddress
      });
      

    Even though you have those two options, there's a third and better option if you have control over the code that actually gets the objects from the data source. If you know you need those two pieces of data, you should create a single method that queries the datasource a single time to get all of the data rather than querying once per piece of data.

提交回复
热议问题