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