我有以下两个清单:
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 :(得分:1)
使用Linq .Intersect
。为了实现这一目标,您的课程需要覆盖Equals
和GetHashCode
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());