IEqualityComparer<T>接口:
成员:
bool Equals(T x, T y)
-
实现此方法可为类型 T 提供自定义相等比较。
如果指定的对象相等,则为 true;否则为 false。
- class MyEqualityComparer<T> : IEqualityComparer<T>
- {
- public bool Equals(T x, T y)
- {
- //转为string类型(为接下来stmp.Length做准备)
- string stmp = x as string;
- if (stmp != null)
- {
- //如果字符串长度为2则不算重复
- if (stmp.Length == 2)
- {
- return false;
- }
- }
- //比较哈希值
- if (x.GetHashCode() == y.GetHashCode())
- return true;
- else
- return false;
- }
- public int GetHashCode(T obj)
- {
- return obj.GetHashCode();
- }
- }
- class Program
- {
- static int Main()
- {
- //源数据
- string[] names = { "贤静","喵喵","Monsoul","柒夜","钱卓文","吴国军","张三","李四","王五" ,"喵喵","Monsoul"};
- //判断重复
- var query = names.Distinct(new MyEqualityComparer<string>());
- foreach (var q in query)
- {
- Console.WriteLine("{0}", q);
- }
- Console.ReadKey();
- return 0;
- }
- }