gpt4 book ai didi

c# - 合并两个动态列表并覆盖值

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:57 25 4
gpt4 key购买 nike

我有两个动态列表,每个列表项都包含三个属性:'Id' (int)、'LikesRed' (bool) 和 'LikesBlue' (bool)。

我想合并这两个列表,按“Id”对每个项目进行分组,但我也想用任何“真”值覆盖任何“假”值。

例如,这是我的两个列表的数据:

List1

{ Id = 1, LikesRed = True, LikesBlue = False }
{ Id = 2, LikesRed = True, LikesBlue = False }
{ Id = 4, LikesRed = False, LikesBlue = True }

List2

{ Id = 1, LikesRed = False, LikesBlue = True }
{ Id = 3, LikesRed = False, LikesBlue = True }
{ Id = 4, LikesRed = True, LikesBlue = False }

这是我的预期结果:

{ Id = 1, LikesRed = True, LikesBlue = True }
{ Id = 2, LikesRed = True, LikesBlue = False }
{ Id = 3, LikesRed = False, LikesBlue = True }
{ Id = 4, LikesRed = True, LikesBlue = True }

我已经使用以下方法合并了两个列表(但项目未分组):

var results = list1.Concat(list2);

我还尝试使用 LINQ 对此列表中的项目进行分组(它有效,但我不确定我能/应该用它做什么):

var final = from x in results
group x by x.Id into g
select g;

任何人都可以就如何实现我的目标提供任何建议吗?

最佳答案

只需检查组中是否有任何项目的值设置为 true:

from x in list1.Concat(list2)
group x by x.Id into g
select new {
Id = g.Key,
LikesRed = g.Any(x => x.LikesRed),
LikesBlue = g.Any(x => x.LikesBlue)
}

关于c# - 合并两个动态列表并覆盖值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30123127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com