-
I created a Emp class
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; } } -
I just Apply Group by command into EmpList then at return statement i got runtime exception that
An unhandled exception of type ‘System.InvalidCastException’ occurred in ConsoleApplication5.exe
Additional information:
Unable to cast object of type ‘WhereSelectEnumerableIterator
2[System.Linq.IGrouping2[System.Int32,ConsoleApplication5.Emp],<>f__AnonymousType03[System.Int32,System.Double,System.Double]]' to type 'System.Collections.Generic.IEnumerable1[ConsoleApplication5.EmpGroup]’.
I also share the code which i have written.
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. I also Created a class for EmpGroup to handle the grouping data.
class EmpGroup
{
public Int32 EmpDeptId { get; set; }
public double SalarySum { get; set; }
public double AverageSalary { get; set; }
}
You cannot cast from anonymous to your type, even if they have the same fields. You should edit your LINQ
selectto create a newEmpGroup: