操作集合以生成精简版本

  • 本文关键字:版本 集合 操作 c# c#-4.0
  • 更新时间 :
  • 英文 :


我目前被一小部分功能难住了,我似乎无法理解。

首先,我有一个Stock类,如下所示:

public class Stock
{
    public int Id;
    public int LocationId;
    public int Quantity;
}

CCD_ 2日志是从数据库返回的,这些日志是由另一项功能产生的。日志表示为List<Stock>集合,但我需要添加相同IDLocationID组合的每个对象的Quantity属性,例如:

原始数据集:

ID:1位置:1数量:20

ID:1位置:2数量:30

ID:1位置:1数量:30

ID:2位置:2数量:20

ID:1位置:2数量:30

ID:1位置:1数量:100

应返回:

浓缩数据集:

ID:1位置:1数量:150

ID:1位置:2数量:60

ID:2位置:2数量:20

重申一下:数据集是从数据库动态返回的,不能保证会有每个ID&CCD_ 8组合和I需要得到的数据集在CCD_ 9和CCD_。

不确定最有效的方法,这阻碍了我在项目中的进展,任何建议或方法都将不胜感激。我有点认为这真的是一个知识差距,但我一直找不到任何合适/符合我要求的东西(我想这是一个很奇怪的要求)。

非常感谢,

Andy

最好在数据库上这样做,但也可以使用GroupBy来实现完全相同的效果:

public class Stock
{
    public int Id;
    public int LocationId;
    public int Quantity;
}
static void Main(string[] args)
{
    var list = new List<Stock>()
        {
            new Stock(){ Id = 1, LocationId = 1, Quantity = 20},
            new Stock(){ Id = 1, LocationId = 2, Quantity = 30},
            new Stock(){ Id = 1, LocationId = 1, Quantity = 30},
            new Stock(){ Id = 2, LocationId = 2, Quantity = 20},
            new Stock(){ Id = 1, LocationId = 2, Quantity = 30},
            new Stock(){ Id = 1, LocationId = 1, Quantity = 100},
        };
    var grouped = list.GroupBy(c => new {Id = c.Id, LocationId = c.LocationId})
            .Select(g => new 
                 { 
                      Id = g.Key.Id, 
                      LocationId = g.Key.LocationId, 
                      Quantity = g.Sum(a => a.Quantity) 
                  });
    foreach(var group in grouped.OrderBy(c => c.Id))
    {
        Console.WriteLine("Id:{0} - LocationId:{1} - Quantity:{2}", group.Id, 
                 group.LocationId, group.Quantity);
    }
}

使用GroupBy执行此操作:

var grouped = (from s in stocks
                group s by new { s.Id, s.LocationId }
                    into grp
                    select new Stock()
                    {
                        Id = grp.Key.Id,
                        LocationId = grp.Key.LocationId,
                        Quantity = grp.Sum(x => x.Quantity)
                    }).ToList();

我更喜欢使用类似以下的SQL查询:

select id, location, sum(quantity) quant from stocktable group by id, location

这有助于在数据库中完成计算,从而在性能方面帮助您。由于数据库服务器无论如何都会读取所有数据并将其提供给应用层,因此不会对性能造成影响,而且在简单性方面也会有所收获。

您可以使用Enumerable.GroupBy执行分组,使用Enumerable.Aggregate(或者在本例中使用专门的Sum)执行聚合。

大致如下:

IEnumerable<Tuple<int, int, int>> result =
    stocks.GroupBy(stock => new { id = stock.Id, locationId = stock.LocationId},
                   (key, s) => new { key.id, key.locationId, total = s.Sum(ss => ss.Quantity) });
foreach (var result in results)
{
    Console.WriteLine(result.id);
    Console.WriteLine(result.locationId);
    Console.WriteLine(result.total);
}

最新更新