Paul Paul - 1 month ago 16
C# Question

Dynamic Linq - How to select parent objects from child properties

In my example, I have Libraries and Books.. I need to return libraries that have a certain book. I can do this fine using standard LINQ Where(.Any()), but having difficulty using Dynamic Linq.

Below is example code. My error occurs on object l4.

protected void Page_Load(object sender, EventArgs e)
{
List<Library> libraries = new List<Library>();
libraries.Add( new Library() { Name = "New York" }); // NO BOOKS FOR NY

List<Book> books = new List<Book>();
books.Add(new Book() { Title = "Colors" });
books.Add(new Book() { Title = "Gardening for Noobs" });
libraries.Add(new Library() {Name = "Boston", Books = books });

// GET NEW YORK LIBRARY
List<Library> l1 = libraries.Where(x => x.Name == "New York").ToList(); // STANDARD
List<Library> l2 = libraries.AsQueryable().Where("Name = \"New York\"").ToList(); // DLINQ

// GET LIBRARIES WITH BOOK = COLORS
List<Library> l3 = libraries.Where(x => x.Books != null && x.Books.Any(a => a.Title == "Colors")).ToList(); // STANDARD
List<Library> l4 = libraries.AsQueryable().Where("Books.any(Title = \"Colors\"").ToList(); // ERROR: No property or field 'Title' exists in type 'Library'

}


public class Library
{
private string _name;
private List<Book> _books;
public string Name
{
get { return _name; }
set { _name = value; }
}
public List<Book> Books
{
get { return _books; }
set { _books = value; }
}
}

public class Book
{
private string _title;
public string Title
{
get { return _title; }
set { _title = value; }
}
}

Answer

You missed one bracket and null cheking. Now it works fine

   List<Library> l4 = libraries.AsQueryable().Where("Books != null && Books.any(Title = \"Colors\")").ToList();

Update: I think that problem not in this part your code: https://dotnetfiddle.net/F2uTie