使用 Linq 在 Epplus 工作表中选择分组的最大值和最小值

Selecting grouped max and min in a Epplus worksheet with Linq

我有一个 Epplus Excel 工作表,看起来像这样。

我想按组列(在 A 列中)进行分组,然后 select 最大值和最小值。我的 group by 子句中有些地方不太正确,出现错误:Cannot apply indexing with [] to ExcelRangeBase.

var maxMinGrouped = from cells in _dataSheet.Cells["A:H"]
                    group cells by cells["A:A"].Value into g //pull "Group" column into group
                    select new
                    {
                        Group = cells["A:A"].Value,
                        MaxDailyIndex = g.Max(c => c.Value),
                        MinDailyIndex = g.Min(c => c.Value)
                    };

我正在努力实现的 SQL。

SELECT Group
    ,MAX(Col_E) AS MaxDailyIndex
    ,MIN(Col_E) AS MinDailyIndex
FROM Worksheet
GROUP BY Group

请记住,单元格集合是一个 2x2 矩阵,因此您需要先将单元格分组到行中,然后才能分组到行组中。我对 linq 的查询表示法很生疏,但这里是如何使用点表示法来做到这一点:

[TestMethod]
public void Grouped_Row_Test()
{
    //

    var existingFile = new FileInfo(@"c:\temp\Grouped.xlsx");
    using (var pck = new ExcelPackage(existingFile))
    {
        var _dataSheet = pck.Workbook.Worksheets.First();

        //Group cells by row
        var rowcellgroups = _dataSheet
            .Cells["A:H"]
            .GroupBy(c => c.Start.Row);

        //Now group rows the column A; Skip the first row since it has the header
        var groups = rowcellgroups
            .Skip(1)
            .GroupBy(rcg => rcg.First().Value);

        //Reproject the groups for the min/max values; Column E = 5
        var maxMinGrouped = groups
            .Select(g => new
            {
                Group = g.Key,
                MaxDailyIndex = g.Select(o => o.First(rc => rc.Start.Column == 5)).Max(rc => rc.Value),
                MinDailyIndex = g.Select(o => o.First(rc => rc.Start.Column == 5)).Min(rc => rc.Value)
            });

        maxMinGrouped
            .ToList()
            .ForEach(mmg => Console.WriteLine("{{Group: \"{0}\", Min={1}, Max={2}}}", mmg.Group, mmg.MinDailyIndex, mmg.MaxDailyIndex));
    }
}

在我向您的 excel table:

中输入一些随机数据后,在控制台中给出了这个
{Group: "3", Min=0, Max=88}
{Group: "4", Min=6, Max=99}