我有一份对调查(评估)的回复表,一个地区可以提交多个评估,但我只想要每个区域的最新评估回复。
以下是我的数据,标有*的记录将是我想要返回的记录
{
"chart": {
"caption": "Total Profit Calculation",
"subcaption": "Last month",
"yAxisname": "Amount (In USD)",
"numberprefix": "$",
"connectordashed": "1",
"sumlabel": "Total {br} Profit",
"positiveColor": "#6baa01",
"negativeColor": "#e44a00",
"paletteColors": "#0075c2,#1aaf5d,#f2c500",
"baseFontColor": "#333333",
"baseFont": "Helvetica Neue,Arial",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"showBorder": "0",
"bgColor": "#ffffff",
"showShadow": "0",
"canvasBgColor": "#ffffff",
"canvasBorderAlpha": "0",
"divlineAlpha": "100",
"divlineColor": "#999999",
"divlineThickness": "1",
"divLineDashed": "1",
"divLineDashLen": "1",
"usePlotGradientColor": "0",
"showplotborder": "0",
"showXAxisLine": "1",
"xAxisLineThickness": "1",
"xAxisLineColor": "#999999",
"showAlternateHGridColor": "0"
},
"data": [
{
"label": "Online sales",
"value": "420000"
},
{
"label": "Store Sales",
"value": "710000"
},
{
"label": "Total Sales",
"issum": "1"
},
{
"label": "Fixed Costs",
"value": "-250000"
},
{
"label": "Variable Costs",
"value": "-156000"
},
{
"label": "COGS",
"value": "-310000"
},
{
"label": "Promotion Costs",
"value": "-86000"
},
{
"label": "Total Costs",
"issum": "1",
"cumulative": "0"
}
]
}
到目前为止,这是我的linq,但它只返回2个回复
AsessmentID AssessmentDate Status AreaID Response Category
1 01/01/2016 Complete 1 1 A
1 01/01/2016 Complete 1 2 B
1 01/01/2016 Complete 1 4 C
2 05/01/2016 Complete 1 5* A
2 05/01/2016 Complete 1 4* B
2 05/01/2016 Complete 1 5* C
3 02/01/2016 Complete 2 1* A
3 02/01/2016 Complete 2 2* B
3 02/01/2016 Complete 2 4* C
4 03/01/2016 Complete 3 5* A
4 03/01/2016 Complete 3 4* B
4 03/01/2016 Complete 3 5* C
5 04/01/2016 Draft 3 3 A
5 04/01/2016 Draft 3 2 B
5 04/01/2016 Draft 3 3 C
答案 0 :(得分:0)
你可以这样做:
var results = db.Answers
.Where(x => x.Status == Status.Complete)
.GroupBy(x => x.AreaID) //group by AreaID
.Select(x => new //project onto anonymous type with the data we need
{
//the AreaID
AreaID = x.Key,
//get a collection for the responses we need
Responses = x
//Group by the date of the assessment
.GroupBy(r => r.AssessmentDate)
//order descending so we get the last responses
.OrderByDescending(r => r.Key)
//take only the first in the list (latest)
.Take(1)
//project the ordered result extracting the properties we want to show
.SelectMany(r => r.Select(ri => new { ri.AssessmentDate, ri.Response}))
})
//enumerate
.ToList();
使用此代码打印到控制台:
foreach (var g in results)
{
Console.WriteLine("AreaID: {0}", g.AreaID);
Console.WriteLine("Date Response");
foreach (var r in g.Responses)
Console.WriteLine("{0} {1}", r.AssessmentDate.ToShortDateString().PadRight(10,' '), r.Response);
Console.WriteLine();
}
你应该得到这个:
AreaID: 1
Date Response
5/1/2016 5
5/1/2016 4
5/1/2016 5
AreaID: 2
Date Response
2/1/2016 1
2/1/2016 2
2/1/2016 4
AreaID: 3
Date Response
3/1/2016 5
3/1/2016 4
3/1/2016 5
希望这有帮助!