標籤:http io for re c ar
GroupBy是按照Item的hashCode來分組的,所以Item最好是override GetHashCode()方法
namespace ConsoleApplication5{ class Program { static void Main(string[] args) { var list = new List<User>(); for (int i = 0; i < 5; i++) { var user = new User { Id = i, Name = i + " user name" }; list.Add(user); } var other = new User { Id = 2, Name = "test 2" }; list.Add(other); var groups = list.GroupBy(u => u);//直接分組 var result = from g in groups select new KeyValuePair<string, User> ( key: g.First().Name, value: g.First() ); //因為User重寫了GetHashCode(),所以temp的結果只有5個item var temp = result.ToList(); } } public class User:IEquatable<User> { public int Id { get; set; } public string Name { get; set; } public bool Equals(User other) { return other != null && this.Id == other.Id; } public override int GetHashCode() { return this.Id.GetHashCode(); } }}
如果不想重寫GetHashCode(),可以指定屬性進行分組
{ class Program { static void Main(string[] args) { var list = new List<User>(); for (int i = 0; i < 5; i++) { var user = new User { Id = i, Name = i + " user name" }; list.Add(user); } var other = new User { Id = 2, Name = "test 2" }; list.Add(other); var groups = list.GroupBy(u => u.Id); var result = from g in groups select new KeyValuePair<string, User> ( key: g.First().Name, value: g.First() ); //結果還是5個 var temp = result.ToList(); } } public class User:IEquatable<User> { public int Id { get; set; } public string Name { get; set; } }}
參考:http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden