是的,C# 的 DistinctBy
方法可以处理自定义类型。DistinctBy
是 LINQ 扩展方法,它允许你根据指定的属性或表达式对集合中的元素进行去重。为了使用 DistinctBy
处理自定义类型,你需要实现 IEquatable
接口,并在你的自定义类中重写 Equals
和 GetHashCode
方法。
以下是一个示例:
using System; using System.Collections.Generic; using System.Linq; public class Person : IEquatable { public string Name { get; set; } public int Age { get; set; } public Person(string name, int age) { Name = name; Age = age; } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; Person person = (Person)obj; return Age == person.Age && string.Equals(Name, person.Name); } public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + (Name != null ? Name.GetHashCode() : 0); hash = hash * 23 + Age; return hash; } } } class Program { static void Main(string[] args) { List people = new List { new Person("Alice", 30), new Person("Bob", 25), new Person("Alice", 30), new Person("Charlie", 22) }; var distinctPeople = people.DistinctBy(p => p.Name); foreach (var person in distinctPeople) { Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } } }
在这个示例中,我们创建了一个 Person
类,实现了 IEquatable
接口,并重写了 Equals
和 GetHashCode
方法。然后我们使用 DistinctBy
方法根据 Name
属性对 people
列表进行去重。