LINQ with Skip and Take

时间:2013-03-13 12:53:18

标签: c# linq skip take

我使用下面的代码从IEnumerable中获取一些项目,但它总是将源返回为null并计为0,实际上IEnumerable

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

当我尝试访问a时,它已计入0。这里出了什么问题?

enter image description here

1 个答案:

答案 0 :(得分:25)

请注意,代码中的变量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
相关问题