第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

C#
梵蒂岡之花 2021-07-02 10:07:26
我有一個包含 4 列的數(shù)據(jù)表,如下所示:    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";我按供應(yīng)商、發(fā)票列對表進行了分組,并使用以下 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條經(jīng)驗 獲得超8個贊

您需要稍微修飾一下 GroupKeys 對象。由于它是一個引用類型,并且 GroupBy 使用的是Default Equality Comparer,它的部分檢查將測試引用相等性,這將始終返回 false。


您可以通過覆蓋Equals和GetHashCode方法來調(diào)整您的 GroupKeys 類以測試結(jié)構(gòu)是否相等。例如,這是由 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);

    }

}


查看完整回答
反對 回復(fù) 2021-07-03
  • 1 回答
  • 0 關(guān)注
  • 261 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號