tags:

views:

181

answers:

5

It's probably a really basic question, but I can't find the answer anywhere.

I'm trying to loop through the input and put the results into an array using C#. From what I read the array has to have the number of elements set first.

Is there a way to just loop through and have the array number of elements dependent on the number of inputs?

TIA

A: 

You want to use a List.

Anon.
+7  A: 

Use a List object so that you can add the results of each iteration in your loop to the List until you have processed all of the input. Then you won't have to keep track of indices / sizes of the array.

The List class has a ToArray() method that you can use after the loop, if you want to store the results in an array. You can either return the array from your method, or clear out the List object after converting it to an array, in order to keep from having extra copies of the data lying around.

David
Fernando brings up a good point about the ArrayList. You can call the same methods on an ArrayList that you can call on a List.
David
Definitely what you need is a List object and to use ToArray method
Zied
thanks for the info. Exactly what I needed.
+2  A: 

If you know the input length, you can initialize the array with that value. Otherwise, you should use a List for a strongly typed collection or an ArrayList.

If your input is an IEnumerable, you can use List.AddRange to add all the values without the need to loop.

You should note that the List and the ArrayList works exactly the way you want. As the docs states, they use "an array whose size is dynamically increased as required".

Fernando
+1: good point, and thanks for bringing up the ArrayList. I assumed with my answer that the input size won't always be the same.
David
A: 

have a look at the ArrayList collection. You can give it an an initial allocation size, and you can also Add items to it.

The capacity of a ArrayList is the number of elements the ArrayList can hold. As elements are added to a ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly.

Of course, it will be more efficient to preallocate it to a reasonable size than to add items one at a time from 0 - but it will work either way.

John Knoeller
I'd only use an ArrayList if you're stuck in time at .Net 1.1: http://stackoverflow.com/questions/725459/c-when-should-i-use-list-and-when-should-i-use-arraylist
Lance McNearney
@Lance: When you don't know what version of .NET you have available or you don't know the data type at compile time, ArrayList is the best choice. Read the question again.
John Knoeller
A: 

And even better, use generic lists whenever possible. Since they came out in 2.0, I don't think I've ever used a plain ArrayList.

List<string> myNames = new List<string>();
myNames.Add("kevin");
string[] myNamesTurnedToStringArray = nyMames.ToArray();

Taking things one step further, I find that nearly every time I need a collection, I need it for more then a few simple statements. If you find that you are hitting your list all over your codebase, you might consider subclassing the List

public class Widgets : List<Widgets> // Widgest class defined elsewhere
{
    public Widgets() : base() {}
    public Widgets(IEnumerable<Widgets> items) : base(items) {}

    public Widget GetWidgetById(int id)
    {
        // assuming only one ID possible
        return this.Where(w => w.id == id).Single(); 
    }

    public string[] GetAllNames()
    {
        return this.Select(w => w.Name).ToArray();
    }
}

//... later in some other class ....

Widgets w = new Widgets(dataFromDatabase);
Widget customerWidget = w.GetWidgetById(customerWidgetId);
string[] allNames = w.GetAllNames();

This is a nice OOPy way of encapsulating your list functionality in one place & often is a great way to separate your concerns organically.

Kevin Won