Linq Group通过C#.net

时间:2012-08-16 11:08:49

标签: linq-to-objects

  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. 我只是按命令将组应用到EmpList然后在return语句中我得到运行时异常

  3.   

    ConsoleApplication5.exe中出现未处理的“System.InvalidCastException”类型异常

    其他信息:

      

    无法转换类型为'WhereSelectEnumerableIterator 2[System.Linq.IGrouping 2 [System.Int32,ConsoleApplication5.Emp],<> f__AnonymousType0 3[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; }
        }
    

1 个答案:

答案 0 :(得分:1)

即使它们具有相同的字段,您也无法从匿名转换为您的类型。您应该编辑LINQ select以创建新的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;

        }