天真的我最開始以為可以寫成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
}
