为了账号安全,请及时绑定邮箱和手机立即绑定

C# Linq GroupBy 方法对于匿名和非匿名类型的工作方式不同

C# Linq GroupBy 方法对于匿名和非匿名类型的工作方式不同

C#
梵蒂冈之花 2021-07-02 10:07:26
我有一个包含 4 列的数据表,如下所示:    private static DataSet dataSet;    private const string tableName = "MyTable";    private const string columnName1 = "Supplier";  //Column names    private const string columnName2 = "Invoice";    private const string columnName3 = "Item";    private const string columnName4 = "Amount";我按供应商、发票列对表进行了分组,并使用以下 linq 查询计算了金额的总和:    private static DataTable GroupQueryA(DataTable dataTable)    {        DataTable groupedTable = dataTable.AsEnumerable()            .GroupBy(r => new { Key1 = r.Field<string>(columnName1), Key2 = r.Field<string>(columnName2) })            .Select(g => new GroupSum            {                Key1 = g.Key.Key1,                Key2 = g.Key.Key2,                Sum = g.Sum(x => x.Field<double>(columnName4))            }).PropertiesToDataTable<GroupSum>();        return groupedTable;    }我声明的 GroupSum 类型为:    private class GroupSum    {        public string Key1 { get; set; }        public string Key2 { get; set; }        public Double Sum { get; set; }    }
查看完整描述

1 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

您需要稍微修饰一下 GroupKeys 对象。由于它是一个引用类型,并且 GroupBy 使用的是Default Equality Comparer,它的部分检查将测试引用相等性,这将始终返回 false。


您可以通过覆盖Equals和GetHashCode方法来调整您的 GroupKeys 类以测试结构是否相等。例如,这是由 ReSharper 生成的:


private class GroupKeys

{

    public string Key1 { get; set; }

    public string Key2 { get; set; }


    public override int GetHashCode()

    {

        unchecked

        {

            return ((Key1 != null ? Key1.GetHashCode() : 0) * 397) ^ (Key2 != null ? Key2.GetHashCode() : 0);

        }

    }


    public override bool Equals(object obj)

    {

        if (ReferenceEquals(null, obj))

            return false;

        if (ReferenceEquals(this, obj))

            return true;

        if (obj.GetType() != this.GetType())

            return false;


        return Equals((GroupKeys)obj);

    }


    public bool Equals(GroupKeys other)

    {

        if (ReferenceEquals(null, other))

            return false;

        if (ReferenceEquals(this, other))

            return true;


        return string.Equals(Key1, other.Key1)

               && string.Equals(Key2, other.Key2);

    }

}


查看完整回答
反对 回复 2021-07-03
  • 1 回答
  • 0 关注
  • 225 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信