Linux 拨号vps windows公众号手机端

C#中如何使Intersect正确识别自定义类型

lewis 7年前 (2018-03-16) 阅读数 11 #程序编程
文章标签 c#

要使Intersect方法正确识别自定义类型,需要实现IEqualityComparer接口来对自定义类型进行比较。以下是一个示例代码:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Student> list1 = new List<Student>
        {
            new Student { Id = 1, Name = "Alice" },
            new Student { Id = 2, Name = "Bob" },
            new Student { Id = 3, Name = "Charlie" }
        };

        List<Student> list2 = new List<Student>
        {
            new Student { Id = 2, Name = "Bob" },
            new Student { Id = 4, Name = "David" },
            new Student { Id = 5, Name = "Eve" }
        };

        var intersectedStudents = list1.Intersect(list2, new StudentComparer());

        foreach (var student in intersectedStudents)
        {
            Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
        }
    }

    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class StudentComparer : IEqualityComparer<Student>
    {
        public bool Equals(Student x, Student y)
        {
            return x.Id == y.Id && x.Name == y.Name;
        }

        public int GetHashCode(Student obj)
        {
            return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();
        }
    }
}

在这个示例中,定义了一个Student类,并实现了IEqualityComparer接口来比较两个Student对象。然后,在Main方法中,创建了两个Student对象的列表,并使用Intersect方法找到两个列表中共同存在的元素。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门