Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在LINQ中使用GroupBy和Sum?_C#_Linq_Group By_Linq To Objects - Fatal编程技术网

C# 如何在LINQ中使用GroupBy和Sum?

C# 如何在LINQ中使用GroupBy和Sum?,c#,linq,group-by,linq-to-objects,C#,Linq,Group By,Linq To Objects,在下面的查询中,我正在使用SelectMany处理GroupBy和Sum。有人能告诉我如何对两个字段求和,以及如何对几个字段进行分组和排序吗 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

在下面的查询中,我正在使用SelectMany处理GroupBy和Sum。有人能告诉我如何对两个字段求和,以及如何对几个字段进行分组和排序吗

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();
对象:

List<DataProperty> allData = new List<DataProperty>();         
如果GroupBy在下面的查询中编码不同,没有求和,您也可以告诉我怎么做吗

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();

不太清楚你想要什么-像这样的东西

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)

这是从ColdFusion重写C#之前的查询:请将其添加到您的问题中,以便可以正确格式化。
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();
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)