Is it possible to introduce a loop into an array without specifying how large the array is in C #?

This is probably really the main question, but I cannot find the answer anywhere.

I am trying to skip input and put the results into an array using C #. From what I read, the number of elements should be set in the array.

Is there a way to simply execute a loop and have a number of array elements depending on the number of inputs?

TIA

+3
source share
5 answers

, , . / .

List ToArray(), , . , List , , .

+8

, . List ArrayList.

IEnumerable, List.AddRange, .

, List ArrayList , . , ", ".

+3

List.

0

, , ,. 2.0, , - ArrayList.

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

, , , , . , , 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();

OOPy .

0

ArrayList. , Add .

ArrayList capacity is the number of elements that an ArrayList can contain. As items are added to the ArrayList, capacity is automatically increased as needed by redistribution. Capacity can be reduced by calling TrimToSize or setting the Capacity property explicitly.

Of course, it will be more efficient to distribute it to a reasonable size than to add elements one at a time from 0, but it will work anyway.

-1
source

Source: https://habr.com/ru/post/1730006/


All Articles