1. 程式人生 > 實用技巧 >C# 使用Enumerable.Range 列印數字

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