LINQ Group by key是一个对象

时间:2016-02-15 08:18:45

标签: c# linq

我有一个这个对象的数组:

public class WorkingOrderContract : BaseContract, IEquatable<WorkingOrderContract>
{
    public string Id { get; set; }
    public string Customer { get; set; }
    public string CategoryId { get; set; }
    public int ResourceId { get; set; }
    public virtual ResourceContract Resource { get; set; }
    public virtual CategoryContract Category { get; set; }
    public WorkingOrderEnum EWorkingOrder { get; set; }
    public TimeFlagEnum ETimeFlag { get; set; }

    public bool Equals(WorkingOrderContract other)
    {
        return this.Id == other.Id;
    }
}

由json文件加载。

我使用此代码进行分组,但它无效

var woListGrupped = this._workingOrderList.GroupBy(wo => wo.Category,
                               wo => wo,
                               (k, g) => new OdlByCategoryContract(k, g.ToList())
                               ).ToList();

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要删除wo => wo

var woListGrupped = this._workingOrderList.GroupBy(wo => wo.Category,
                               (k, g) => new OdlByCategoryContract(k, g.ToList())
                               ).ToList();

正如@MarcinJuraszek正确指出的那样,除此之外,OdlByCategoryContract应该实施EqualsGetHashCode,以便正确地对列表进行分组。