2016-08-30 62 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 :) –