lambda表达式的distinct去重的坑坑坑坑坑

天真的我最开始以为可以写成list.distinct(x=>x.name);以为这样就可以按照name去重了,结果是不行的。这里记录下正确的用法。

1.这里是针对int集合  可以满足

#region 对数字集合的去重
//List<int> list = new List<int> { 1,1,2,3,4,5,5,6,6,7,7,7 };
//foreach (var item in list)
//{
// Console.Write(item+" ");
//}
//var res = list.Distinct();
//Console.WriteLine();
//Console.WriteLine("********************************");
//foreach (var item in res)
//{
// Console.Write(item+" ");
//}
//可以看到 对于数字来说 distinct可以实现去重
#endregion

 2.对对象集合使用 失败

#region 对非数字类型去重失败的方法
//List<Student> list = new List<Student>
//{
// new Student{name="张三",age=20},
// new Student{name="张三",age=20},
// new Student{name="李四",age=20},
// new Student{name="李四",age=20},
// new Student{name="王五",age=20},
// new Student{name="赵六",age=20},
// new Student{name="陈启",age=20},
// new Student{name="陈启",age=20},
//};
//foreach (var item in list)
//{
// Console.Write(item.name + " ");
//}
//var res = list.Distinct();
//Console.WriteLine();
//Console.WriteLine("********************************");
//foreach (var item in res)
//{
// Console.Write(item.name + " ");
//}
//运行这段代码 可以看到去重失败了 下面来看正确的做法
#endregion

 3.这才是正确的方法

class Program
{
static void Main(string[] args)
{
#region 对非数字类型去重正确
List<Student> list2 = new List<Student>
{
new Student{name="张三",age=20},
new Student{name="张三",age=20},
new Student{name="李四",age=20},
new Student{name="李四",age=20},
new Student{name="王五",age=20},
new Student{name="赵六",age=20},
new Student{name="陈启",age=20},
new Student{name="陈启",age=20},
};
foreach (var item in list2)
{
Console.Write(item.name + " ");
}
var res2 = list2.Distinct(new userCompare());
Console.WriteLine();
Console.WriteLine("********************************");
foreach (var item in res2)
{
Console.Write(item.name + " ");
}
//声明一个类 实现IEqualityComparer接口
//实现方法bool Equals(T x, T y);
//int GetHashCode(T obj);
//然后再内部写上比较的字段和属性 比较才能成功 才能去重
#endregion
Console.ReadLine();
}
}


public class Student
{
public int age { get; set; }
public string name { get; set; }
}


public class userCompare : IEqualityComparer<Student>
{

#region IEqualityComparer<user> Members

public bool Equals(Student x, Student y)
{

return x.name.Equals(y.name);

}

public int GetHashCode(Student obj)
{

return obj.name.GetHashCode();

}

#endregion

}

猜你喜欢

转载自www.cnblogs.com/yagamilight/p/12305538.html