链接IEnumerable <T>扩展方法的首选(高效和可读)方式是什么?

BQ.*_*BQ. 6 .net c# ienumerable extension-methods

如果我试图在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();
    }
Run Code Online (Sandbox Code Playgroud)

这是示例对象图:

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; }
}
Run Code Online (Sandbox Code Playgroud)

Rex*_*x M 1

这取决于底层 LINQ 提供程序的工作方式。对于 LINQ to Objects,在这种情况下,两者都需要或多或少相同的工作量。但这是最直接(最简单)的例子,除此之外就很难说了。