合并两个动态列表并覆盖值

时间:2015-05-08 11:49:49

标签: c# asp.net linq

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

我想合并两个列表,按照'Id'对每个项目进行分组,但我还想用任何'true'值覆盖任何'false'值。

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

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;

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

2 个答案:

答案 0 :(得分:5)

只需检查组中的任何项是否已将值设置为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)
}

答案 1 :(得分:-1)

您可以先按照您已经执行过的操作对列表进行分组,然后使用Zip覆盖您的偏好设置值。