LINQ to SQL Condition
HI!
I want to make a LINQ to SQL request that handles two different conditions. One of them is listed in the function below. The condition I want to include in the function below is that I want to be able to request persons of any age. How do I re开发者_运维百科write this functions so it handles a request for 1. Persons of a certain age or 2: Persons of any age.
public IQueryable test(int age)
{
var persons = from p in db.Person
where p.age = age
select new
{
p.name
};
return persons;
}
public IQueryable test(Nullable<int> age)
{
var persons = from p in db.Person
where p.age = age.HasValue ? age.Value : p.age
select new
{
p.name
};
return persons;
}
If you pass null
to this function you will get persons of any age.
var persons = from p in db.Person
select new
{
p.name,
p.age
};
if (age > 0) // or declare a bool to check age needs to be filtered.
{
persons = persons.Where(p => p.age == age);
}
- Write two queries.
- Use query composition.
精彩评论