【问题标题】:Combine values from 2 object lists based on on common variable根据公共变量组合来自 2 个对象列表的值
【发布时间】:2020-07-07 22:36:36
【问题描述】:

我有两个列表:列表 a,列表 b

var a1= new A
{
  Name = "XYZ",
  Id = "123"
};
var a2= new A
{
  Name = "UVW",
  Id = "567"
};
var a = new List<A>()
{
    a1,
    a2
};

public class A
{
    public string Name{ get; set; }
    public string Id{ get; set; }
}


var b1= new B
{
  Location = "US",
  Id = "123"
};
var b2= new B
{
  Location = "IN",
  Id = "567"
};
var b = new List<B>()
{
    b1,
    b2
};

public class B
{
    public string Location{ get; set; }
    public string Id{ get; set; }
}

请注意,Id 在 A 类和 B 类中都很常见。最终目标是拥有一个包含 A 类和 B 类成员值的列表:

var output = new List<AB>()
{
  ab1,
  ab2
}

public class AB
{
    public string Id{ get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
}

或者更新列表 a 以包含列表 b 中的值?

我将如何在 C# 中做到这一点?

【问题讨论】:

  • 如果您描述您的实际目标,它可能会有所帮助。你想通过这样做来达到什么目的?我觉得你把一个相当简单的问题复杂化了。
  • 也许显示一些你想要的样本输入和输出。
  • 这能回答你的问题吗? How to join two Lists based on common property

标签: c# linq arraylist


【解决方案1】:

您可以使用Join 获取基于Id 的常用数据并填充AB,如下代码:

var output = aList.Join(bList,
    a => a.Id,
    b => b.Id,
    (a, b) => new AB
    {
        Id = a.Id,
        Location = b.Location,
        Name = a.Name
    }).ToList();

演示

foreach(var item in output)
{
   Console.WriteLine($"Id:{item.Id}, Name : {item.Name}, Location:{item.Location}");
}

结果

Id:123, Name : XYZ, Location:US
Id:567, Name : UVW, Location:IN

dotnetfiddle 中的演示:https://dotnetfiddle.net/3ZbK6c

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2016-01-20
    • 2023-02-26
    • 2019-03-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    相关资源
    最近更新 更多