首页 > 代码库 > C# GroupBy
C# GroupBy
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。