LINQ与跳过并带 [英] LINQ with Skip and Take

查看:128
本文介绍了LINQ与跳过并带的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

当我尝试访问a时,其计数为0.这里有什么问题吗?

When i try to access a it has count 0. Anything goes wrong here?

推荐答案

请记住,您代码中的变量a查询本身.它不是查询执行结果.当您使用即时窗口观看查询时(实际上与推迟执行的查询有关,否则您将获得结果而不是查询),它将始终显示

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

{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

这篇关于LINQ与跳过并带的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆