如何作为LINQ查询的一部分执行代码

时间:2010-09-01 13:56:56

标签: .net asp.net-mvc linq linq-to-entities

我有一个如下所示的查询:

    var results = from person
                  where <here I need to do something like if person is of type 
Employee, call person.GetSalary() > 100000 but if the person is of type Contractor, I need to execute 
several lines of code before doing a person.GetSalary() > 100000 
                  select new {person.Name}

困难在于构造where子句。有人可以帮我完成这个查询吗?

1 个答案:

答案 0 :(得分:3)

您始终可以编写执行逻辑检查的方法,并在单独的where子句中调用它。要使用LINQ-to-Entities执行此操作,必须先使用AsEnumerable()实现结果:

bool CheckEmployeeOrContractorSalary( Person p, decimal salaryLevel )
{
   // put your employee and contractor logic here...
   if( p is Employee ) {
       return p.GetSalary() > salaryLevel; }
   else if( p is Contractor ) {
       // ... your complex logic...
       return p.GetSalary() > salaryLevel; }
   else
       // ??? 
       return false;
}

现在你可以写:

var results = from person in (
                  (from p in person select new { p.Name } ).AsEnumerable())
              where CheckEmployeeOrContractorSalary( person, 100000 )
              select new {person.Name};