C# 使用Enumerable.Range 打印数字
static void Main(string[] args) { var list1 = Enumerable.Range(0, (int)Math.Pow(2, 22)).ToList(); var list2 = new List<int>(list1); list2.Add(1); Console.WriteLine($"list1.Capacity={list1.Capacity}"); Console.WriteLine($"list2.Capacity={list2.Capacity}"); Console.ReadLine(); }
一、源码
public static IEnumerable<int> Range(int start, int count) { long num = (long) start + (long) count - 1L; if (count < 0 || num > (long) int.MaxValue) throw Error.ArgumentOutOfRange("count"); else return Enumerable.RangeIterator(start, count); } private static IEnumerable<int> RangeIterator(int start, int count) { for (int i = 0; i < count; ++i) yield return start + i; }
二、写我们自己的时间序列DataRange
// implementation public static System.Collections.Generic.IEnumerable<DateTime> DateRange(DateTime begin, DateTime end) { for (var iterator = begin; iterator <= end; iterator = iterator.AddDays(1)) { yield return iterator; } } // usage foreach (var date in DateRange(DateTime.Now.Date,DateTime.Now.Date.AddDays(5).AddHours(3))) { Console.WriteLine(date.ToLocalTime()); }