using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.Windows.System.PerfCounters { public sealed class Program { static void Main(string[] args) { List<MyClass> s = new List<MyClass>(); s.Add(new MyClass { Age = 78 }); s.Add(new MyClass { Age = 18 }); s.Add(new MyClass { Age = 18 }); s.Add(new MyClass { Age = 8 }); s.Add(new MyClass { Age = 8 }); s.Add(new MyClass { Age = 58 }); s.Add(new MyClass { Age = 98 }); s.Add(new MyClass { Age = 98 }); s.Sort(); var q = s.Distinct(new MyClass()).ToList(); foreach (var item in q) { Console.WriteLine(item.Age); } List<int> a = new List<int>(); a.Add(1); a.Add(2); a.Add(1); a.Add(5); a.Add(1); a.Add(6); var b = a.Distinct(); foreach (var item in b) { Console.WriteLine(item); } } } class MyClass : IComparable<MyClass>, IEqualityComparer<MyClass> { public int Age { get; set; } public int CompareTo(MyClass other) { return this.Age.CompareTo(other.Age); } public bool Equals(MyClass x, MyClass y) { return x.Age == y.Age; } public int GetHashCode(MyClass obj) { return obj.Age.GetHashCode(); } } }
实现Distinct方法。
同样的还有sort还有其他的方法。