Geeks With Blogs

News

The Wrecking Bawl Destructuring query language, one keyword at a time.

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.

 

 

Posted on Wednesday, April 28, 2010 7:17 AM all tech stuff , C# , general .Net stuff | Back to top


Comments on this post: creating a list of consecutive integers in c#

# re: creating a list of consecutive integers in c#
Requesting Gravatar...
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.
Left by Alex on Apr 29, 2010 4:12 AM

# re: creating a list of consecutive integers in c#
Requesting Gravatar...
I am reviewing my blogroll and wonder your blog feed has been inactive for a few months or moved somewhere else?

Cheers.
Left by Luciano Evaristo Guerche (Gorše) on Jul 22, 2010 6:27 AM

Your comment:
 (will show your gravatar)


Copyright © Alex Bransky | Powered by: GeeksWithBlogs.net