質問

I'm struggling with GroupBy and Sum in the following query using SelectMany. Could someone show me how to sum two fields as well as how to group by and order by several fields.

var Rows = allData.SelectMany(u => u._rows.Select(t => new
{
  OA = t[4],
  CD = t[5],
  PD = t[0],
  DS = Convert.ToInt32(t[9]),
  CS = Convert.ToInt32(t[10])
}))
// Pseudo-code:
//.GroupBy(CD)
//.GroupBy(OA)
//.GroupBy(PD)
//.Sum(u=> u.DS)
//.Sum(u => u.CS)
.OrderBy(u => u.CD)
.ThenBy(u => u.OA)
.ThenBy(u => u.PD)
.ToList();

Object:

List<DataProperty> allData = new List<DataProperty>();         

DataProperty consists of

private readonly Dictionary<string, string> _headers = new Dictionary<string, string>(); 
private readonly List<string[]> _rows = new List<string[]>();

The original query before the C# rewrite from ColdFusion:

SELECT 
OA,
CD,
PD,               
sum(DS) as DS
sum(CS) as CS
FROM qDistinct
GROUP BY 
CD,
OA,
PD
ORDER BY 
ucaseCD,
OA,
PD

If the GroupBy is coded differently in the following query without Sum, could you also please show me how to do it?

var Rows = allData.SelectMany(u => u._rows.Select(t => new
{
  OA = t[4],
  PD = t[0]      
}))
// Pseudo-code:
//.GroupBy(OA)
//.GroupBy(PD)   
.OrderBy(u => u.OA)
.ThenBy(u => u.PD)
.ToList();
役に立ちましたか?

解決

It's not very clear what you want - something like this?

var Rows = allData.SelectMany(u => u._rows.Select(t => new
{
  OA = t[4],
  CD = t[5],
  PD = t[0],
  DS = Convert.ToInt32(t[9]),
  CS = Convert.ToInt32(t[10])
}))
// group by the combination of CD, OA, and PD
.GroupBy(x => new { x.CD, x,OA, x.PD } )
// sum DS and CS within each group
.Select (g => new {g.Key.CD, 
                   g.Key.OA, 
                   g.Key.PD,  
                   DS = g.Sum(u=> u.DS), 
                   CS = g.Sum(u=> u.CS) 
                  } ) 
.OrderBy(u => u.CD)
.ThenBy(u => u.OA)
.ThenBy(u => u.PD)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top