如何获得在C#中的列表中前N个元素? [英] How to get first N elements of a list in C#?
本文介绍了如何获得在C#中的列表中前N个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我自学C#和我做我的第一个项目。我想使用LINQ查询公交站牌,这样,在任何时候,我可以得到未来5公交车到站时间。如何限制我的查询到第5的结果?
更一般地,我怎么可以在C#中的列表中分得一杯羹? (在Python我会用MYLIST [5]。拿到第5元素)
解决方案
VAR firstFiveItems = myList.Take(5);
或者切片:
VAR secondFiveItems = myList.Skip(5)。取(5);
当然,常常是很方便根据某种为了得到前五个项目:
VAR firstFiveArrivals = myList.OrderBy(I => i.ArrivalTime)。取(5);
I'm teaching myself C# and am doing my first project. I would like to use Linq to query a bus schedule, so that at any time I can get the next 5 bus arrival times. How can I limit my query to the first 5 results?
More generally, how can I take a slice of a list in C#? (In Python I would use mylist[:5] to get the first 5 elements.)
解决方案
var firstFiveItems = myList.Take(5);
Or to slice:
var secondFiveItems = myList.Skip(5).Take(5);
And of course often it's convenient to get the first five items according to some kind of order:
var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);
这篇关于如何获得在C#中的列表中前N个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文