使用LINQ GroupBy按引用对象而不是值对象分组 [英] Using LINQ GroupBy to group by reference objects instead of value objects

查看:182
本文介绍了使用LINQ GroupBy按引用对象而不是值对象分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对记录列表中的多个对象进行分组,而不仅仅是对多个值进行分组.

I want to GroupBy multiple objects in a list of records and not simply multiple values.

我无法分组以使用引用类型对象.我有一个包含Room,Type和DateTime的对象的集合. Room,Type和DateTime都具有与之关联的属性.我已经在房间中添加了IEquateable接口,并且使用了group by时已经足够了类型思维.

I am having trouble getting grouping to work with reference type objects. I have a collection of objects that contain Room, Type, and DateTime. Room, Type, and DateTime all have properties associated with them. I've already added the IEquateable interface to the room and the type thinking that would be enough to with with group by.

var groups = collection
  .Where(g => g.Stage == InventoryStage.StageA)
  .GroupBy(g => new {g.BirthDate, g.Room, g.Type});

为了使此代码起作用,我必须在这些对象上调用我们的特定属性进行分组.这样做的问题是,我需要将复杂的对象存储在分组的关键字"中,以便我可以访问该分组的特定信息

In order for this code to work i have to call our a specific property on these objects to group by. The problem with that is that i need the complex objects stored in the "Key" of the grouping so that i can access that groups specific information

var groups = collection
  .Where(g => g.Stage == InventoryStage.StageA)
  .GroupBy(g => new {
     Birthday = g.BirthDate, 
     RoomName = g.Room.Name, 
     TypeName = g.Type.Name
   });

我最终不得不做^才能使分组工作,但是这些分组丢失了我想要的复杂对象.

I end up having to do ^ to get the grouping to work, however the groups lose the complicated object i wanted.

推荐答案

要完成此任务,您可以为类覆盖Equals()和GetHashCode()方法:

To accomplish this task, you can override Equals() and GetHashCode() methods for your classes:

public class Room {
     public string Name;
     public string Foo;

     public override bool Equals(object obj)
     {
         Room other = obj as Room;
         if (other == null) return false;
         return this.Name == other.Name && this.Foo == other.Foo;
     }

     public override int GetHashCode()
     {
         return (Name.GetHashCode() ^ Foo.GetHashCode()).GetHashCode();
     }
}

此处更复杂的例子

这篇关于使用LINQ GroupBy按引用对象而不是值对象分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆