How to get first N elements of a list in C#?
我想在我的项目中使用LINQ查询一个巴士时刻表,以便在任何时候我都可以得到接下来的5个巴士到达时间。如何将查询限制为前5个结果?
更一般地说,我如何才能在C中对列表进行切片?(在python中,我将使用
1 | var firstFiveItems = myList.Take(5); |
或切片:
1 | var secondFiveItems = myList.Skip(5).Take(5); |
当然,根据某种订单,通常可以方便地获得前五项:
1 | var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5); |
如果有人感兴趣(即使问题不要求这个版本),在C 2中应该是:(我已经按照一些建议编辑了答案)
1 2 | myList.Sort(CLASS_FOR_COMPARER); List<string> fiveElements = myList.GetRange(0, 5); |
和
1 2 | var slice = myList.Skip((pageNumber - 1) * pageSize) .Take(pageSize); |
例1:前五项
1 2 | var pageNumber = 1; var pageSize = 5; |
例2:第二个五项
1 2 | var pageNumber = 2; var pageSize = 5; |
例3:第三个五项
1 2 | var pageNumber = 3; var pageSize = 5; |
If notice to formule parameters
pageSize = 5 andpageNumber is changing, if you want to change number of items in slicing you changepageSize .
为了获得前5个元素,最好使用如下表达式:
或
它将比orderby变量更快,因为LINQ引擎不会因为延迟的执行而扫描所有列表,也不会对所有数组进行排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | class MyList : IEnumerable<int> { int maxCount = 0; public int RequestCount { get; private set; } public MyList(int maxCount) { this.maxCount = maxCount; } public void Reset() { RequestCount = 0; } #region IEnumerable<int> Members public IEnumerator<int> GetEnumerator() { int i = 0; while (i < maxCount) { RequestCount++; yield return i++; } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion } class Program { static void Main(string[] args) { var list = new MyList(15); list.Take(5).ToArray(); Console.WriteLine(list.RequestCount); // 5; list.Reset(); list.OrderBy(q => q).Take(5).ToArray(); Console.WriteLine(list.RequestCount); // 15; list.Reset(); list.Where(q => (q & 1) == 0).Take(5).ToArray(); Console.WriteLine(list.RequestCount); // 9; (first 5 odd) list.Reset(); list.Where(q => (q & 1) == 0).Take(5).OrderBy(q => q).ToArray(); Console.WriteLine(list.RequestCount); // 9; (first 5 odd) } } |