在我的示例中,我有圖書館和書籍。我需要返回具有特定書籍的圖書館。我可以使用標準的LINQ Where(.Any())來做到這一點,但是使用Dynamic Linq有困難。動態Linq - 如何從子屬性中選擇父對象
下面是示例代碼。我的錯誤發生在對象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; }
}
}
謝謝,但我仍然收到相同的錯誤「類型'庫'中沒有屬性或字段'標題'。 – Paul
@保羅試圖檢查我的更新 –
完美!我的System.Linq.Dynamic參考文件不正確。我從NuGet最近更新並解決了這個問題。 – Paul