如果我试图在IEnumerable<T>
对象图的多个级别过滤结果,是否有链接扩展方法的首选方法来执行此操作?
我对任何扩展方法和 lambda 用法持开放态度,但我不希望使用 LINQ 语法来与代码库的其余部分保持一致。
将过滤推送到方法selector
中SelectMany()
还是仅仅链接另一个Where()
方法更好?还是有更好的解决方案?
我将如何确定最佳选择?在这个测试用例中,一切都直接在内存中可用。显然,下面的两个样本目前都产生了相同的正确结果;我只是在寻找一个或另一个(或另一种选择)更受欢迎的原因。
public class Test
{
// I want the first chapter of a book that's exactly 42 pages, written by
// an author whose name is Adams, from a library in London.
public Chapter TestingIEnumerableTExtensionMethods()
{
List<Library> libraries = GetLibraries();
Chapter chapter = libraries
.Where(lib => lib.City == "London")
.SelectMany(lib => lib.Books)
.Where(b => b.Author == "Adams")
.SelectMany(b => b.Chapters)
.First(c => c.NumberOfPages == 42);
Chapter chapter2 = libraries
.Where(lib => lib.City == "London")
.SelectMany(lib => lib.Books.Where(b => b.Author == "Adams"))
.SelectMany(b => b.Chapters.Where(c => c.NumberOfPages == 42))
.First();
}
这是示例对象图:
public class Library
{
public string Name { get; set; }
public string City { get; set; }
public List<Book> Books { get; set; }
}
public class Book
{
public string Name { get; set; }
public string Author { get; set; }
public List<Chapter> Chapters { get; set; }
}
public class Chapter
{
public string Name { get; set; }
public int NumberOfPages { get; set; }
}