Linq的Distinct
public class DA { public int ID { get; set; } } class Program { static void Main(string[] args) { var list = new List<DA>(); var data = new DA(); for (int i = 0; i < 10; i++) { data = new DA { ID = i }; list.Add(data); } for (int i = 0; i < 10; i++) { data = new DA { ID = i }; list.Add(data); } list = list.Select(p => new DA { ID = p.ID }).Distinct(new DAComparint()).ToList(); Console.Read(); } } public class DAComparint : IEqualityComparer<DA> { public bool Equals(DA x, DA y) { if (x == null && y == null) return false; return x.ID == y.ID; } public int GetHashCode(DA obj) { return obj.ToString().GetHashCode(); } }
Linq的Distinct如果针对于引用类型,需要实现IEqualityComparer接口