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

我有一个包含 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; }

    }


梵蒂冈之花
浏览 242回答 1
1回答

守着星空守着你

您需要稍微修饰一下 GroupKeys 对象。由于它是一个引用类型,并且 GroupBy 使用的是Default Equality Comparer,它的部分检查将测试引用相等性,这将始终返回 false。您可以通过覆盖Equals和GetHashCode方法来调整您的 GroupKeys 类以测试结构是否相等。例如,这是由 ReSharper 生成的:private class GroupKeys{&nbsp; &nbsp; public string Key1 { get; set; }&nbsp; &nbsp; public string Key2 { get; set; }&nbsp; &nbsp; public override int GetHashCode()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; unchecked&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ((Key1 != null ? Key1.GetHashCode() : 0) * 397) ^ (Key2 != null ? Key2.GetHashCode() : 0);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public override bool Equals(object obj)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (ReferenceEquals(null, obj))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; if (ReferenceEquals(this, obj))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; if (obj.GetType() != this.GetType())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; return Equals((GroupKeys)obj);&nbsp; &nbsp; }&nbsp; &nbsp; public bool Equals(GroupKeys other)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (ReferenceEquals(null, other))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; if (ReferenceEquals(this, other))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; return string.Equals(Key1, other.Key1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&& string.Equals(Key2, other.Key2);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP