开发者

How to execute code as a part of the LINQ query

开发者 https://www.devze.com 2023-01-13 20:13 出处:网络
I have a query that looks like this: var results = from person where <here I need to do something like if person is of type

I have a query that looks like this:

    var results = from person
                  where <here I need to do something like if person is of type 
Employee, call person.GetSalary() > 100000开发者_如何学Go 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}

The difficulty is in constructing the where clause. Can someone help me complete this query?


You can always write a method that performs your logical check and call it in a separate where clause. To do so with LINQ-to-Entities, you must first materialize the results using 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;
}

Now you can write:

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

精彩评论

暂无评论...
验证码 换一张
取 消