Populating a list of integers in .NET

后端 未结 4 1737
难免孤独
难免孤独 2020-12-10 00:09

I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously:

List

        
相关标签:
4条回答
  • 2020-12-10 00:50

    Here is a short method that returns a List of integers.

        public static List<int> MakeSequence(int startingValue, int sequenceLength)
        {
            return Enumerable.Range(startingValue, sequenceLength).ToList<int>();
        }
    
    0 讨论(0)
  • 2020-12-10 00:51

    I'm one of many who has blogged about a ruby-esque To extension method that you can write if you're using C#3.0:

    
    public static class IntegerExtensions
    {
        public static IEnumerable<int> To(this int first, int last)
        {
            for (int i = first; i <= last; i++)
    { yield return i; } } }

    Then you can create your list of integers like this

    List<int> = first.To(last).ToList();

    or

    List<int> = 1.To(x).ToList();

    0 讨论(0)
  • 2020-12-10 01:00

    LINQ to the rescue:

    // Adding value to existing list
    var list = new List<int>();
    list.AddRange(Enumerable.Range(1, x));
    
    // Creating new list
    var list = Enumerable.Range(1, x).ToList();
    

    See Generation Operators on LINQ 101

    0 讨论(0)
  • 2020-12-10 01:04

    If you're using .Net 3.5, Enumerable.Range is what you need.

    Generates a sequence of integral numbers within a specified range.

    0 讨论(0)
提交回复
热议问题