List<T>是.NET中最常用的一种数据结构了,我们常常把需要操作的对象都放到一个List<T>里面。有的时候,我们需要让List<T>中的数据保持唯一性,也就是说List中的数据不能有重复的项。我们知道,List<T>中可以存放任意的类型,如List<int>,List<string>等。为了剔除List<T>中的重复项,.NET为我们提供了一个Distinct()函数。对于普通类型的List,我们可以直接调用该函数剔除掉List中的重复项。下面是示例代码:
List<int> intInList = new List<int>() { 1, 7, 2, 4, 2, 0, 2, 7 }; List<int> newIntList = intInList.Distinct().ToList(); foreach (int i in newIntList) { Console.Write(i + "\t"); }
下面是数据结果:
1 7 2 4 0 Press any key to continue . . .
上面演示了List<int>这种最基本的List,但是,如果此时我们有一个自定义的类,如Person类,那么上面的代码就无法得到正确的结果。代码如下:
public class Person { public string FirstName; public string LastName; } class Program { static void Main(string[] args) { List<Person> personInList = new List<Person>(); personInList.AddRange(new Person[]{ new Person() { FirstName = "Sheldon", LastName = "Liu" }, new Person() { FirstName = "Aaron", LastName = "Zeng" }, new Person() { FirstName = "Sheldon", LastName = "Liu" }, new Person() { FirstName = "Aaron", LastName = "Zeng" }, }); personInList = personInList.Distinct().ToList(); foreach (var p in personInList) { Console.WriteLine(p.FirstName); } } }
下面是运行结果:
Sheldon Aaron Sheldon Aaron Press any key to continue . . .
可以看到,我们并没有将重复元素去除掉。原因是.NET没办法去比较两个Person实例是否相等。为了让.NET知道两个Person到底谁大,我们需要另外写一个帮助类,该类实现了IEqualityComparer<Person>接口,然后将该类的实例传递到Distinct()中去。这样,.NET就有能力去判断两个Person实例是否相等,也就能从List<Person>中剔除重复项了。代码如下:
public class Person { public string FirstName; public string LastName; } public class PersonComparer : IEqualityComparer<Person> { public bool Equals(Person x, Person y) { if (x.FirstName.Equals(y.FirstName) && x.LastName.Equals(y.LastName)) return true; else return false; } public int GetHashCode(Person obj) { return obj.FirstName.GetHashCode() * obj.LastName.GetHashCode(); } } class Program { static void Main(string[] args) { List<Person> personInList = new List<Person>(); personInList.AddRange(new Person[]{ new Person() { FirstName = "Sheldon", LastName = "Liu" }, new Person() { FirstName = "Aaron", LastName = "Zeng" }, new Person() { FirstName = "Sheldon", LastName = "Liu" }, new Person() { FirstName = "Aaron", LastName = "Zeng" }, }); personInList = personInList.Distinct(new PersonComparer()).ToList(); foreach (var p in personInList) { Console.WriteLine(p.FirstName); } } }
运行结果如下:
Sheldon Aaron Press any key to continue . . .
时间: 2024-10-12 08:14:00