c#对象集合的比较

//如果要比较序列中对象的实际数据而不是仅仅比较它们的引用,则必须在类中实现IEqualityComparer<T> 泛型接口
public class People:IEquatable<People> 
{
    public string Name { get; set; }
    public int Age { get; set; }
    public bool Equals(People other)
    {
        if (other is null)
            return false;
 
        return this.Name == other.Name && this.Age == other.Age;
    }     
}
        
/// <summary>
/// 对象集合比较
/// </summary>
private void Test()
{
    List<People> peoples1 = new List<People> { new People { Name = "张三", Age = 10 }, new People { Name = "小红", Age = 10 } };
    List<People> peoples2 = new List<People> { new People { Name = "张三", Age = 10 }, new People { Name = "小红", Age = 10 } };
    var b = peoples1.SequenceEqual(peoples2); //true
}

 

posted @ 2023-04-11 09:22  vba是最好的语言  阅读(47)  评论(0编辑  收藏  举报