2015-05-08 68 views
1

我有兩個動態列表,每個列表項包括三個屬性:'Id'(int),'LikesRed'(bool)和'LikesBlue'(布爾)。合併兩個動態列表並覆蓋值

我想合併這兩個列表,按照它的'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); 

我也試圖將這個列表中的項目用LI NQ(它的工作原理,但我不知道我能/應該用它做):

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

誰能提供任何意見,我怎麼能實現我的目標是什麼?

+0

https://msdn.microsoft.com/en-us/library/bb545971.aspx – Banana

回答

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

完美,簡單的解決方案! – mmmoustache

-1

您可以第一組列出了IDS有像你已經做了和丹恩使用Zip與您的喜好覆蓋值。