2013-09-28 83 views
1

考慮複雜對象的兩個列表說:合併複雜的對象列表使用聯盟/相交

 var first = new List<Record> 
      { 
       new Record(1, new List<int> { 2, 3 }), 
       new Record(4, new List<int> { 5, 6 }) 
      }; 

     var second = new List<Record> 
      { 
       new Record(1, new List<int> { 4 }) 
      }; 

其中Record定義如下。沒有什麼奇特的,只有一個類IdSecondaryIdentifiers名單。

public class Record 
    { 
     private readonly IList<int> _secondaryIdentifiers; 
     private readonly int _id; 

     public Record(int id, IList<int> secondaryIdentifiers) 
     { 
      _id = id; 
      _secondaryIdentifiers = secondaryIdentifiers; 
     } 

     public IList<int> SecondaryIdentifiers 
     { 
      get { return _secondaryIdentifiers; } 
     } 

     public int Id 
     { 
      get { return _id; } 
     } 
    } 

我怎樣才能工會/興趣使得聯盟和相交操作合併的SecondaryIdentifiers。

 var union = first.Union(second); 
     var intersect = first.Intersect(second); 

聯盟將

  { 
       new Record(1, new List<int> { 2, 3 , 4 }), 
       new Record(4, new List<int> { 5, 6 }) 
      }; 

相交會

  { 
       new Record(1, new List<int> { 2, 3 , 4 }), 
      }; 

我已經試過

我使用first.Union(second, new EqualityComparer())其中EqualityComparer延伸IEqualityComparer<Record>和合並兩個SecondaryIdentifiers嘗試如果兩項比較是平等的,但對我來說似乎有點冒失。

有沒有更好的方法來做到這一點?

回答

1

是否有這樣做的更優雅的方式這

它的意見爲基礎,但我會做到這一點的:

var union = first.Concat(second) 
      .GroupBy(x => x.Id) 
      .Select(g => g.SelectMany(y => y.SecondaryIdentifiers).ToList()) 
      .ToList(); 


var intersect = first.Concat(second) 
       .GroupBy(x => x.Id) 
       .Where(x => x.Count() > 1) 
       .Select(g => g.SelectMany(y => y.SecondaryIdentifiers).ToList()) 
       .ToList(); 

PS:隨意刪除.ToList() S代表懶評價。

0

本應爲工會工作的一部分:

from a in first 
join b in second on a.Id equals b.Id into rGroup 
let ids = a.SecondaryIdentifiers.Union(rGroup.SelectMany(r => r.SecondaryIdentifiers)) 
select new Record(a.Id, ids.ToList()) 

和交叉:

from a in first 
join b in second on a.Id equals b.Id 
select new Record(a.Id, a.SecondaryIdentifiers.Union(b.SecondaryIdentifiers).ToList())