John Louie Dela Cruz John Louie Dela Cruz - 1 year ago 84
C# Question

Select from table using model properties that is not null

I want to select values from table where my model properties that has a value.
This is my Model.

public class Library

public IEnumerable<Books> books { get; set; }
public string BookName { get; set; }
public string Color { get; set; }
public int ShelfNumber { get; set; }

I want to select from table where values are equal to my model property that is filled up.

For Example:

public ActionResult(Library lib)
var b = _bookService.GetBooks();
lib.books = b.Where(x => // select values from table based on the properties that has a value in my model)

How to do this?

Answer Source

Assuming that properties in Books has same names as properties in Library you are probably looking for something like this:

var b = _bookService.GetBooks();

foreach (PropertyInfo p in typeof(Library).GetProperties())
    // skip "books" property
    if (p.Name == "books")

    // skip null values from lib
    if (p.GetValue(lib) == null)

    // build condition dynamically
    var value = Expression.Constant(p.GetValue(lib));
    var param = Expression.Parameter(typeof (Books));
    var predicate = Expression.Lambda<Func<Books, bool>>(
            Expression.Property(param, p.Name), 

    b = b.Where(predicate);

b must be queryable, if it is not change first line to var b = _bookService.GetBooks().AsQueryable();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download