开发者

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);
}


  1. Write two queries.
  2. Use query composition.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜