Linq基於兩個屬性的分組


1、需求

我們看下面的定義

    #region 學生類
    /// <summary>
    /// 學生類
    /// </summary>
    class Student
    {
        /// <summary>
        /// ID
        /// </summary>
        public string ID { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 分數
        /// </summary>
        public float Score { get; set; }

        /// <summary>
        /// 科目
        /// </summary>
        public string Subject
        {
            get;
            set;
        }
    }
    #endregion

我們實例化一組數據

  //實例化一組數據
            List<Student> list = new List<Student>()
            {
                new  Student{ ID="00000001", Name="馬良", Subject="數學", Score=100},
                new  Student{ ID="00000001", Name="馬良",  Subject="語文",Score=99},
                new  Student{ ID="00000001", Name="馬良", Subject="物理", Score=95},
                new  Student{ ID="00000003", Name="馬青", Subject="數學", Score=100},
                new  Student{ ID="00000003", Name="馬青",  Subject="語文",Score=80},
                new  Student{ ID="00000003", Name="馬青", Subject="物理", Score=95},
            };

將list按照ID和name分組,並求分數的和。

2、解決方案

通常的解決解決方案時排序兩次,先用id排一次,再用Name排一次。

今天我們采用一種新的方式。采用匿名對象來存儲id,name的對象。具體實現方案如下

 

           //按照兩個字段進行分組
            var group = from item in list
                        group item by new { item.ID, item.Name } into caca
                        select new { key = caca.Key, sum = caca.Sum(it => it.Score) };

            //將分組數據打印出來
            foreach (var item in group)
            {
                Console.WriteLine("{0},{1}->{2}", item.key.ID, item.key.Name, item.sum);
            }
            Console.ReadKey();

 

解讀上面的代碼,將new { item.ID, item.Name }設定為key,進行檢索。

大功告成

下載代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM