c# - 根据公共变量组合来自 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# 中做到这一点?
解决方案
您可以使用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
我希望你觉得这有帮助。
推荐阅读
- python - 将带有键和值的字符串转换为python dict的最有效方法
- python - 填充numpy数组中的相邻元素
- python - 在 Windows 上编译 scikit-image 以运行测试
- angular - 子组件如何在子组件初始化时控制其自身在父组件中的可见性?
- java - 何时在 CDI 中发送 @Initialized(ApplicationScoped.class) 事件?
- php - Carbon 将天数转换为人类可读的格式
- css - 将自定义样式添加到反应中的引导类。
- python-3.x - 为未经授权的 AWS 服务用户编写 python 测试
- bootstrap-4 - fullcalendar 事件显示两次
- sql - 将区间划分和聚合到桶中