How to execute code as a part of the LINQ query
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};
精彩评论