将列表合并为一个 [英] Merge lists into one

查看:84
本文介绍了将列表合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了以下类似的帖子,这些帖子对我来说真的很难理解.因此,我将其重新发布.很抱歉,如果有人觉得它是重复的.我只有简单的要求

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#在Linq和Lambda中加入/在此处

我有一个像这样的班

public class Person
{
  public int Id{get;set;}
  public string Name{get;set;}
  public string MailingAddress{get;set;}
}

我有如下方法

public IList<Person> GetNames(IList<int> ids)

这将给我下面的人员列表

This will give me List of persons like below

1个山姆""

2"Dev""

4个"Hummy"

4 "Hummy"

我还有另一种类似下面的方法

I have another method like below

 public IList<Person> GetMailingAddress(IList<int> ids)

这将给我下面的人员列表

This will give me List of persons like below

1""ABC"

6""TTT"

2""XYZ"

现在我需要合并两种方法的结果,以便可以得到这样的最终结果

Now I need to merge results of two methods so that I can have my final result like this

1个山姆""ABC"

1 "Sam" "ABC"

2"Dev""XYZ"

2 "Dev" "XYZ"

更新:很抱歉,我没有明确提供测试数据.请在上方查看我的测试数据

UPDATE : I am sorry I didnot clearly give my test data. Please see above my test data

推荐答案

我对您的方法返回的结果感到有些困惑,如果您需要将两个结果结合起来以获得完整的Person对象,那么您可以通过两种方式也许可以使事情正常进行.

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. 如果您可以依赖以相同顺序返回的相同数量的对象,则可以尝试:

  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
});

  • 如果您不能同时使用这两个条件,则可以使用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.

    这篇关于将列表合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆