LINQ with Skip and Take

大城市里の小女人 提交于 2019-11-27 03:51:14

问题


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);
}

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


回答1:


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


来源:https://stackoverflow.com/questions/15385905/linq-with-skip-and-take

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!