从方法加入两个列表后返回列表

时间:2015-04-09 05:25:08

标签: c# asp.net linq return-value

public List<Employee> CallSupportFindAll()
{
List<Employee> list1 = new List<Employee>();
list1 .Add(new Employee { Name = "Emp_1", BasicSalary = 1000, Id = Guid.NewGuid(), HRA = 100, DA = 10});
list1 .Add(new Employee { Name = "Emp_2", BasicSalary = 1000 * 2, Id = Guid.NewGuid(), HRA = 200, DA = 20});
list1 .Add(new Employee { Name = "Emp_3", BasicSalary = 1000 * 3, Id = Guid.NewGuid(), HRA = 300, DA = 30});

List<Employee> list2= new List<Employee>();
list2.Add(new Employee { Name = "Emp_1", TotalSalary = 1110 });
list2.Add(new Employee { Name = "Emp_2", TotalSalary = 2220 });
list2.Add(new Employee { Name = "Emp_3", TotalSalary = 3330 });

var Query = (from emp1 in list1
    join emp2 in list2
    on new { emp1.Name }
    equals new { emp2.Name }
    select new
    {
        emp1.Name,
        emp1.Id,
        emp1.BasicSalary,
        emp1.HRA,
        emp1.DA,
        emp2.TotalSalary
        }).ToList();
return Query.toList();

此行return Query.ToList()给我错误 - 无法隐式将类型“System.Collection.generic.List<Anonymous Type#1>转换为System.Collection.generic.List<Employee>

1 个答案:

答案 0 :(得分:1)

您正在尝试返回anonymous类型而不是List<Employee>

请改为: -

select new Employee
                  {
                     Name = emp1.Name,
                     Id = emp1.Id,
                     BasicSalary = emp1.BasicSalary,
                     HRA = emp1.HRA,
                     DA = emp1.DA,
                     TotalSalary = emp2.TotalSalary
                  });
return Query.ToList();

Alos,你在两个地方不需要ToList,要么在查询中使用它,要么像我一样使用返回类型。