[英]Selecting grouped max and min in a Epplus worksheet with Linq
我有一個看起來像這樣的Epplus Excel工作表。
我想按Group列分組(在A列中),然后選擇max和min。 我的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()
{
//http://stackoverflow.com/questions/30466257/selecting-grouped-max-and-min-in-a-epplus-worksheet-with-linq
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表中輸入一些隨機數據后,在控制台中給出了這個:
{Group: "3", Min=0, Max=88}
{Group: "4", Min=6, Max=99}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.