获取列表项的特定范围(LINQ)

X30*_*61X 5 c# linq

我有这个我正在使用的代码块:

// get the collection of librarys from the injected repository
librarySearchResults = _librarySearchRepository.GetLibraries(searchTerm);

// map the collection into a collection of LibrarySearchResultsViewModel view models
libraryModel.LibrarySearchResults =
    librarySearchResults.Select(
        library =>
        new LibrarySearchResultsViewModel
        {
            Name = library.Name,
            Consortium = library.Consortium,
            Distance = library.Distance,
            NavigateUrl = _librarySearchRepository.GetUrlFromBranchId(library.BranchID),
            BranchID = library.BranchID
        }).ToList();
Run Code Online (Sandbox Code Playgroud)

所有这一切都是取结果GetLibraries(searchTerm),返回一个LibrarySearchResult对象列表,并将它们映射到一个列表LibrarySearchResultsViewModel.

虽然这适用于小型结果集,但一旦我进入1000,它真的开始拖动,在完成转换之前大约需要12秒.

我的问题 :

由于我在这里使用分页,我实际上只需要显示在大型结果集中返回的一小部分数据.有没有利用类似的方式Take()或者GetRange(),这样的转换仅发生于我需要显示的记录?在1,000条记录中,我只想获取20到40条记录,并将它们转换为视图模型.

我也是关于改进或重构此代码的任何建议.

Zbi*_*iew 21

使用SkipTake:

// take records from 20 to 40
var records = librarySearchResults.Skip(20).Take(20);
Run Code Online (Sandbox Code Playgroud)

您可以轻松地对其进行分页(您需要pagepageSize).

另一方面,你在ToList那里使用,考虑使用just IEnumerable,转换到list可能会耗费大量时间,特别是对于大型数据集.


Mik*_*ran 7

您可以使用Skip()Take()一起启用分页.

var idx = // set this based on which page you're currently generating
librarySearchResults.Skip(idx * numitems).Take(numitems).Select(lib => ...);
Run Code Online (Sandbox Code Playgroud)