2016-08-30 68 views
0

我有以下兩個列表:找出兩個列表之間的共同元件用lambda表達式

var firstList = new List<ProgramInfo>() 
{ 
    new ProgramInfo {Name = "A", ProgramId = 1, Description = "some text1"}, 
    new ProgramInfo {Name = "C", ProgramId = 2, Description = "some text2"}, 
    new ProgramInfo {Name = "D", ProgramId = 3, Description = "some text3"}, 
    new ProgramInfo {Name = "E", ProgramId = 4, Description = "some text4"} 
}; 

var secondList = new List<ProgramInfo>() 
{ 
    new ProgramInfo {Name = "C", ProgramId = 2, Description = "some text1"}, 
    new ProgramInfo {Name = "D", ProgramId = 3, Description = "some text2"}, 
}; 

這兩個列表都在運行時產生的,我必須從兩個該列表的選擇根據程序ID的共同的ProgramInfo

例如,在上述例子的情況下,輸出應該是

var thirdList = new List<ProgramInfo>() 
{ 
    new ProgramInfo {Name = "C", ProgramId = 2, Description = "some text1"}, 
    new ProgramInfo {Name = "D", ProgramId = 3, Description = "some text2"}, 
}; 

    public class ProgramInfo 
    { 
    public string Name { get; set; } 
    public int ProgramId { get; set; } 
    public string Description { get; set; } 
    } 

有人建議我怎麼能做到這一點使用lambda表達式?

+0

這可能是一個錯字,但不知道 - 我的' secondList'和'thirdList'的意思是''一些text2「'和''一些text3」'就像上面的列表中一樣? –

+1

不知道我在這裏看到很多研究努力... –

回答

1

使用Linq .Intersect。對於工作類需要重寫EqualsGetHashCode

var thirdList = firstList.Intersect(secondList); 

您還可以指定一個IEqualityComparer而不是重寫功能:

public class Comparer : IEqualityComparer<ProgramInfo> 
{ 
    public bool Equals(ProgramInfo x, ProgramInfo y) 
    { 
     return x.Name == y.Name && 
      x.ProgramId == y.ProgramId && 
      x.Description == y.Description; 
    } 

    public int GetHashCode(ProgramInfo obj) 
    { 
     return obj.Name.GetHashCode()^
      obj.ProgramId.GetHashCode()^
      obj.Description.GetHashCode(); 
    } 
} 

var thirdList = firstList.Intersect(secondList, new Comparer()); 
+0

非常感謝。我沒有想到IEqualityComparer。 – App

+0

@App - 酷:)如果你發現這有幫助,請考慮標記爲解決和upvoting :) –