C# LINQ 与 Skip and Take
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15385905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ with Skip and Take
提问by
I used the below code to take some items from IEnumerable
, but it is always returning the source as null and count as 0 and actually there are items exists in IEnumerable
我使用下面的代码从 中获取一些项目IEnumerable
,但它总是将源返回为 null 并计为 0,实际上存在项目IEnumerable
private void GetItemsPrice(IEnumerable<Item> items, int customerNumber)
{
var a = items.Skip(2).Take(5);
}
When i try to access a
it has count 0
. Anything goes wrong here?
当我尝试访问a
它时有计数0
。这里有什么问题吗?
采纳答案by Sergey Berezovskiy
Remember, that variable a
in your code is a query itself. It is not result of query execution. When you are using Immediate Window to watch query (actually that relates to queries which have deferred execution otherwise you will have results instead of query), it will always show
请记住,a
代码中的变量本身就是一个查询。它不是查询执行的结果。当您使用即时窗口查看查询时(实际上这与延迟执行的查询有关,否则您将获得结果而不是查询),它将始终显示
{System.Linq.Enumerable.TakeIterator<int>}
count: 0
source: null
You can verify that with this code, which obviously has enough items:
您可以使用此代码验证这一点,它显然有足够的项目:
int[] items = { 1, 2, 3, 4, 5, 6, 7 };
var a = items.Skip(2).Take(3);
So, you should execute your query to see results of query execution. Write in Immediate Window:
因此,您应该执行查询以查看查询执行的结果。在立即窗口中写入:
a.ToList()
And you will see results of query execution:
您将看到查询执行的结果:
Count = 3
[0]: 3
[1]: 4
[2]: 5