• ADADADADAD

    C#中如何使Intersect正确识别自定义类型[ 编程知识 ]

    编程知识 时间:2024-12-04 17:02:59

    作者:文/会员上传

    简介:

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

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

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

    ```csharp

    using System;

    using System.Collections.Generic;

    using System.Linq;

    class Program

    {

    static void Main()

    {

    List list1 = new List

    {

    new Student { Id = 1, Name = "Alice" },

    new Student { Id = 2, Name = "Bob" },

    new Student { Id = 3, Name = "Charlie" }

    };

    List list2 = new List

    {

    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

    {

    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方法找到两个列表中共同存在的元素。

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

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: c