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; }
}
}
}
一个Linq Group By 和Sum的范例
最新推荐文章于 2022-05-20 14:57:53 发布