对展开的LINQ结果集进行分组

本文关键字:结果 LINQ | 更新日期: 2023-09-27 18:22:09

我有一个查询,它会产生一个扁平的结果集,但我实际上并不希望它扁平化,我需要对它进行分组。

var test = (from a in _activityNoteService.GetAll()
    from l in a.ActivityNoteLines
    where l.POItemId == poItem.Id && a.ActivityTypeId == 1
    from s in l.StockCatalogueItem.StockInventoryItems
    where s.OriginalActivityNoteLineID == l.Id
    select new
    {
      sii = s.Id,
      sci = s.StockCatalogueItem,
      po = a.PurchaseOrder
    }).ToList();

sii值是我感兴趣的唯一记录,scipo值是常见的(即重复的)。我如何重构它,使其返回一个sci、一个posii记录列表

对展开的LINQ结果集进行分组

var test = (from a in _activityNoteService.GetAll()
    from l in a.ActivityNoteLines
    where l.POItemId == poItem.Id && a.ActivityTypeId == 1
    from s in l.StockCatalogueItem.StockInventoryItems
    where s.OriginalActivityNoteLineID == l.Id
    group s by new { sci = s.StockCatalogueItem, po = a.PurchaseOrder  } into g
    select new
    {
      ListOfSii = g.Select(s => s.Id),
      g.Key.sci,
      g.Key.po
    }).ToList();