我创建了一个 Emp 类
class Emp { public Emp() { } public Emp(Int64 empId, string empName, double empSalary,int empDeptId) { this.EmpID = empId; this.EmpName = empName; this.EmpSalary = empSalary; this.EmpDeptId = empDeptId; } public Int64 EmpID { get; set; } public string EmpName { get; set; } public double EmpSalary { get; set; } public Int32 EmpDeptId { get; set; } }
我只是将 Group by 命令应用到 EmpList 然后在返回语句中我得到运行时异常
ConsoleApplication5.exe 中发生了“System.InvalidCastException”类型的未处理异常
附加信息:
无法转换类型为“WhereSelectEnumerableIterator
2[System.Linq.IGrouping
2[System.Int32,ConsoleApplication5.Emp],<>f__AnonymousType03[System.Int32,System.Double,System.Double]]' to type 'System.Collections.Generic.IEnumerable
1[ConsoleApplication5.EmpGroup]”的对象。
我还分享了我编写的代码。
public IEnumerable<EmpGroup> GroupByDeptId()
{
var numberGroups =from result in empList
group result by result.EmpDeptId into groupingData
select new
{
EmpDeptId = groupingData.Key,
SalarySum = groupingData.Sum(p => p.EmpSalary),
AverageSalary = groupingData.Average(p => p.EmpSalary)
};
return (IEnumerable<EmpGroup>)numberGroups;
}
`3。我还为 EmpGroup 创建了一个类来处理分组数据。
class EmpGroup
{
public Int32 EmpDeptId { get; set; }
public double SalarySum { get; set; }
public double AverageSalary { get; set; }
}