一个Linq Group By 和Sum的范例

  • Post author:
  • Post category:其他


转自:http://www.cnblogs.com/sskset/archive/2012/09/06/2674055.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var Items = new List<SortItem>();

            Items.AddRange(new SortItem[] { 
                new SortItem(){ GroupId = 1, Id=1, Count = 1, Weight = 100 },
                new SortItem(){ GroupId = 1, Id=1, Count = 2, Weight = null },
                new SortItem(){ GroupId = 1, Id =2, Count = 3, Weight = 300 },
                new SortItem(){ GroupId = 2, Id=1, Count = 2, Weight = 200 },
                new SortItem(){ GroupId = 2, Id=2, Count = 2, Weight = 200 },
                new SortItem(){ GroupId = 2, Id=3, Count = 4, Weight = null },
                new SortItem(){ GroupId = 3, Id=3 ,Count = 2, Weight = null },
                new SortItem(){ GroupId = 1, Id =2, Count = 6, Weight = 300 },
            });

            var data = (from a in Items
                        group a by new { a.GroupId, a.Id } into b
                        orderby new ComparerItem() { GroupId = b.Key.GroupId, Id = b.Key.Id } descending
                        select new
                        {
                            GroupId = b.Key.GroupId,
                            Id = b.Key.Id,
                            Count = b.Sum(c => c.Count),
                            Weight = b.Sum(c => c.Weight)
                        }).OrderBy(t => t.GroupId).ThenBy(t => t.Id);


            foreach (var anItem in data)
                Console.WriteLine("GroupId:{0} Id:{1} Count:{2} Weight:{3}", anItem.GroupId, anItem.Id, anItem.Count, anItem.Weight);

            Console.ReadKey();
        }

        class ComparerItem : IComparable
        {
            public int GroupId { get; set; }
            public int Id { get; set; }

            public int CompareTo(object obj)
            {
                var tem = (ComparerItem)obj;

                if (this.GroupId == tem.GroupId)
                {
                    if (this.Id > tem.Id) return 1;
                    else if (this.Id < tem.Id) return -1;

                    return 0;
                }
                else if (this.GroupId > tem.GroupId)
                {
                    return 1;
                }

                return -1;
            }
        }


        class SortItem
        {
            public int GroupId { get; set; }
            public int Id { get; set; }
            public int Count { get; set; }
            public int? Weight { get; set; }
        }
    }
}