Conditional Multiple Fields Searching and Filtering in LINQ

后端 未结 3 1526
执笔经年
执笔经年 2021-01-03 02:05

Assuming that we have the following table:

Person:
  PersonID,
  Name,
  Age,
  Gender

And we are providing a search function that allows u

3条回答
  •  抹茶落季
    2021-01-03 02:56

    Try code like this

           string personName = txtPersonName.Text;
           int personAge = Convert.ToInt32(txtAge.Text);
           var opportunites =  from p in this.DataContext.Persons
                                select new
                                {
                                    p.PersonID,
                                    p.Name,
                                    p.Age,
                                    p.Gender
                                };
    
            if (personsID != 0)
                opportunites = opportunites.Where(p => p.PersonID == personID);
    
            if (personName != string.Empty)
                opportunites = opportunites.Where(p => p.Name.StartsWith(personName));
    
            if (personAge != 0)
                opportunites = opportunites.Where(p => p.Age == personAge);
    

    This will work fine. If personName is not given it will be not add to where, and if given then it will added.

提交回复
热议问题