一个Linq Group By 和Sum的范例

70 篇文章 0 订阅
11 篇文章 0 订阅
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; }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值