首页 > 解决方案 > 根据公共变量组合来自 2 个对象列表的值

问题描述

我有两个列表:列表 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# 中做到这一点?

标签: c#linqarraylist

解决方案


您可以使用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

我希望你觉得这有帮助。


推荐阅读