使用LINQ GroupBy按引用对象而不是值对象进行分组

时间:2016-08-04 08:01:11

标签: c# linq grouping ienumerable iequatable

我希望GroupBy记录列表中的多个对象,而不仅仅是多个值。

我无法使用引用类型对象进行分组。我有一组包含Room,Type和DateTime的对象。 Room,Type和DateTime都具有与之关联的属性。我已经将IEquateable接口添加到房间,并且类型思维对于group by已经足够了。

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

为了使这段代码能够工作,我必须调用我们对这些对象的特定属性进行分组。问题在于我需要存储在" Key"中的复杂对象。分组,以便我可以访问该组特定信息

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

我最终必须做^才能使分组工作,但是这些组失去了我想要的复杂对象。

2 个答案:

答案 0 :(得分:2)

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

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();
     }
}

查看here以获取更复杂的示例

答案 1 :(得分:0)

  1. 您可以覆盖包含这些属性的主类中的Equals + GetHashCode,而不是使用GroupBy中的匿名类型。
  2. 另一种方法是实现自定义IEqualityComparer<YourMainType>。您可以将其实例用于GroupBy的重载。
  3. 您的RoomType可以覆盖Equals + GetHashCode或/并实施IEquatable<T>。实施IEquatable / IEquatable<>并不充分,因为GroupBy首先使用GetHashCode确定哈希码,然后才开始将对象与Equals进行比较,以便&{1}} #39;是初始过滤器。
  4. 以下是Room类的示例:

    public class Room:IEquatable<Room>
    {
        public Room(string name)
        {
            Name = name;
        }
    
        public string Name { get; }
    
        /// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
        /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(Room other)
        {
            return String.Equals(this.Name, other?.Name);
        }
    
        /// <summary>Determines whether the specified object is equal to the current object.</summary>
        /// <returns>true if the specified object  is equal to the current object; otherwise, false.</returns>
        /// <param name="obj">The object to compare with the current object. </param>
        public override bool Equals(object obj)
        {
            if(ReferenceEquals(this, obj))
                return true;
            Room other = obj as Room;
            return this.Equals(other);
        }
    
        /// <summary>Serves as the default hash function. </summary>
        /// <returns>A hash code for the current object.</returns>
        public override int GetHashCode()
        {
            return Name?.GetHashCode() ?? Int32.MinValue;
        }
    }
    

    现在,您甚至可以将复杂类型用作匿名类型的属性。