使用lambda表达式查找两个列表之间的公共元素
本文关键字:之间 列表 元素 两个 表达式 lambda 查找 使用 | 更新日期: 2023-09-27 18:04:57
我有以下两个列表:
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表达式做到这一点吗?
使用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());