Conditional Multiple Fields Searching and Filtering in LINQ

后端 未结 3 1528
执笔经年
执笔经年 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.

    0 讨论(0)
  • 2021-01-03 02:59

    One alternative which I have used in SQL which could be implemented in Linq too is

    var p = from p in Person
           where p.Name == Name_TextBox || Name_TextBox == String.Empty
           select p;
    

    (Note that your 'linq' is using SQL syntax, which won't compile. Also you can't declare a var as you are doing without directly assigning a value)

    0 讨论(0)
  • 2021-01-03 03:00

    why not use the null coalescing operator? eg.

    var products = from a in context.products where a.ID == (productID ?? a.ID) select a;

    This works really well on my system

    0 讨论(0)
提交回复
热议问题