-->

LINQ与跳跃和Take(LINQ with Skip and Take)

2019-07-21 12:08发布

我用下面的代码,以从一些项目IEnumerable ,但它始终是返回的源为空,算作0,居然有项目存在IEnumerable

private void GetItemsPrice(IEnumerable<Item> items, int customerNumber)
{
    var a = items.Skip(2).Take(5);
}

当我试图访问a已计数0 。 有什么差错吗?

Answer 1:

请记住,该变量a在你的代码是一个查询本身 。 它不会导致查询执行的 。 当您使用即时窗口观看查询(实际上是涉及具有延迟执行,否则你就会有结果,而不是查询的查询),它会始终显示

{System.Linq.Enumerable.TakeIterator<int>}
    count: 0
    source: null

您可以验证此代码,这显然有足够的项目:

int[] items = { 1, 2, 3, 4, 5, 6, 7 };
var a = items.Skip(2).Take(3);

所以,你应该执行查询看到查询执行的结果 。 写立即窗口:

a.ToList()

你会看到查询执行的结果:

Count = 3
    [0]: 3
    [1]: 4
    [2]: 5


文章来源: LINQ with Skip and Take
标签: c# linq skip take