0
  1. 我创建了一个 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; }
    }
    
  2. 我只是将 Group by 命令应用到 EmpList 然后在返回语句中我得到运行时异常

ConsoleApplication5.exe 中发生了“System.InvalidCastException”类型的未处理异常

附加信息:

无法转换类型为“WhereSelectEnumerableIterator 2[System.Linq.IGrouping2[System.Int32,ConsoleApplication5.Emp],<>f__AnonymousType0 3[System.Int32,System.Double,System.Double]]' to type 'System.Collections.Generic.IEnumerable1[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; }
    }
4

1 回答 1

1

您不能从匿名转换为您的类型,即使它们具有相同的字段。您应该编辑您的 LINQselect以创建一个新的EmpGroup

public IEnumerable<EmpGroup> GroupByDeptId()
        {

            var numberGroups =from result in empList
                              group result by result.EmpDeptId into groupingData
                              select new EmpGroup() // here
                              {
                                  EmpDeptId = groupingData.Key,
                                  SalarySum = groupingData.Sum(p => p.EmpSalary),
                                  AverageSalary = groupingData.Average(p => p.EmpSalary) 
                              };

               return (IEnumerable<EmpGroup>)numberGroups;

        }
于 2012-08-16T11:20:48.633 回答