The Wrecking Bawl

Destructuring query language, one keyword at a time.


News


If there's already a way to get a List<int> of consecutive integers without a loop in C#, I don't know what it is, so I created a method for it.

        public static List<int> GetIntegerListFromRangeUsingLoop(int start, int end) {
            if (end < start) {
                throw new ArgumentException("Faulty parameter(s) passed: lower bound cannot be less than upper bound.");   
            }
            List<int> returnList = new List<int>(end - start + 1);
            for(int i = start; i <= end; i++) {
                returnList.Add(i);
            }
            return returnList;
        }

 UPDATE:

I was pointed to Enumerable.Range(), so I updated my code.

        public static List<int> GetIntegerListFromRangeUsingEnumerableRange(int start, int end) {
            IEnumerable<int> list = Enumerable.Range(start, end - start + 1);
            return list.ToList();
        }

Then I used the StopWatch class in my unit tests to compare the two methods.

Results:

GetIntegerListFromRangeUsingEnumerableRange averaged 6.5 milliseconds.

GetIntegerListFromRangeUsingLoop averaged 0.43 milliseconds.

Wow.  Apparently Enumerable.Range() is a lot slower than using a loop.

 

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Comments

Gravatar # re: creating a list of consecutive integers in c#
Posted by Alex on 4/29/2010 4:12 AM
Good question Jack, it would surprise me a little if ToList() was a large portion of the 6.5 ms but I'll test it out when I get a chance.
Gravatar # re: creating a list of consecutive integers in c#
Posted by Luciano Evaristo Guerche (Gorše) on 7/22/2010 6:27 AM
I am reviewing my blogroll and wonder your blog feed has been inactive for a few months or moved somewhere else?

Cheers.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: