source

C# 배열에 값 추가

nicesource 2023. 6. 18. 16:07
반응형

C# 배열에 값 추가

C#부터 시작해서 배열에 값을 추가해야 합니다. 예를 들어 다음과 같습니다.

int[] terms;

for(int runs = 0; runs < 400; runs++)
{
    terms[] = runs;
}

PHP를 사용해 본 사람들을 위해, 제가 C#에서 하려고 하는 것은 다음과 같습니다.

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;
}

당신은 이렇게 할 수 있습니다.

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

또는 목록을 사용할 수 있습니다. 목록의 장점은 목록을 인스턴스화할 때 배열 크기를 알 필요가 없다는 것입니다.

List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsList.Add(value);
}

// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();

편집: 목록의 루프에 대한 <List<T>의 각 루프에 비해 2배 이상 저렴한 영역, b) 어레이에서 루프하는 것이 List<T>에서 루프하는 것보다 약 2배 저렴하며, c) 어레이에서 루프하는 것이 List<에서 루프하는 것보다 5배 저렴합니다.(우리 대부분이 하는) 각각을 위해 사용합니다.

Linq의 방법사용하는 Concat은 이것을 단순하게 만듭니다.

int[] array = new int[] { 3, 4 };

array = array.Concat(new int[] { 2 }).ToArray();

결과 3,4,2

C# 3으로 작성하는 경우 한 줄로 작성할 수 있습니다.

int[] terms = Enumerable.Range(0, 400).ToArray();

이 코드 조각은 사용자가 시스템에 대한 사용 지침을 가지고 있다고 가정합니다.파일 맨 위에 있는 링크입니다.

반면에 동적으로 크기를 조정할 수 있는 것을 찾고 있다면 PHP의 경우처럼 보입니다(실제로 배운 적이 없습니다). 그러면 int[] 대신 List를 사용하는 것이 좋습니다.이 코드는 다음과 같습니다.

List<int> terms = Enumerable.Range(0, 400).ToList();

그러나 항 [400]을 값으로 설정하여 401번째 원소를 단순히 추가할 수는 없습니다.대신 다음과 같이 Add()를 호출해야 합니다.

terms.Add(1337);

까지 2019년까지 할 수 .Append,Prepend용사를 LinQ

using System.Linq;

그리고 NET 6.0에서:

terms = terms.Append(21);

또는 NET 6.0 이하 버전

terms = terms.Append(21).ToArray();

어레이를 사용하는 방법에 대한 답변이 여기에 나와 있습니다.

하지만 C#에는 System이라는 매우 편리한 것이 있습니다.컬렉션

많은 컬렉션이 내부적으로 어레이를 사용하지만, 컬렉션은 어레이를 사용하는 멋진 대안입니다.

예를 들어 C#에는 PHP 배열과 매우 유사하게 작동하는 List라는 컬렉션이 있습니다.

using System.Collections.Generic;

// Create a List, and it can only contain integers.
List<int> list = new List<int>();

for (int i = 0; i < 400; i++)
{
   list.Add(i);
}

다른 사람들이 설명한 것처럼 목록을 중개자로 사용하는 것이 가장 쉬운 방법이지만, 입력이 배열이고 데이터를 목록에 보관하는 것을 원하지 않기 때문에 성능에 대해 걱정할 수 있습니다.

가장 효율적인 방법은 새 배열을 할당한 다음 배열을 사용하는 것입니다.복사 또는 배열.복사 위치. 목록의 끝에 항목을 추가하려는 경우에는 어렵지 않습니다.

public static T[] Add<T>(this T[] target, T item)
{
    if (target == null)
    {
        //TODO: Return null or throw ArgumentNullException;
    }
    T[] result = new T[target.Length + 1];
    target.CopyTo(result, 0);
    result[target.Length] = item;
    return result;
}

원하는 경우 대상 인덱스를 입력으로 하는 Insert 확장 메서드에 대한 코드를 게시할 수도 있습니다.이것은 조금 더 복잡하고 정적 방법 Array를 사용합니다.1-2회 복사합니다.

Thracx의 답변을 기반으로 합니다(답변할 포인트가 부족합니다).

public static T[] Add<T>(this T[] target, params T[] items)
    {
        // Validate the parameters
        if (target == null) {
            target = new T[] { };
        }
        if (items== null) {
            items = new T[] { };
        }

        // Join the arrays
        T[] result = new T[target.Length + items.Length];
        target.CopyTo(result, 0);
        items.CopyTo(result, target.Length);
        return result;
    }

이렇게 하면 둘 이상의 항목을 배열에 추가하거나, 배열을 매개 변수로 전달하여 두 배열을 결합할 수 있습니다.

먼저 배열을 할당해야 합니다.

int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
    terms[runs] = value;
}
int ArraySize = 400;

int[] terms = new int[ArraySize];


for(int runs = 0; runs < ArraySize; runs++)
{

    terms[runs] = runs;

}

그렇게 코드를 만들 겁니다.

C# 배열은 고정 길이이며 항상 인덱싱됩니다.Motti의 솔루션을 사용하십시오.

int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

이 배열은 400바이트의 연속 블록인 고밀도 배열로, 물건을 놓을 수 있습니다.동적 크기의 배열을 사용하려면 목록<int>를 사용합니다.

List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
    terms.Add(runs);
}

int[]도 List<int>도 연관 배열이 아닙니다. C#에서는 사전<>이 됩니다.배열과 목록은 모두 조밀합니다.

배열에 요소를 쉽게 추가할 수는 없습니다.fallen888에 설명된 대로 주어진 위치에 요소를 설정할 수 있지만, 다음을 사용할 것을 권장합니다.List<int> 는또.Collection<int>대신에, 그리고 사용합니다.ToArray()배열로 변환해야 하는 경우.

어레이가 정말로 필요한 경우 다음과 같은 것이 가장 단순합니다.

using System.Collections.Generic;

// Create a List, and it can only contain integers.
List<int> list = new List<int>();

for (int i = 0; i < 400; i++)
{
   list.Add(i);
}

int [] terms = list.ToArray();

한 가지 접근 방식은 LINQ를 통해 어레이를 채우는 것입니다.

배열을 하나의 요소로 채우고 싶다면 간단히 쓸 수 있습니다.

string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();

또한 배열을 여러 요소로 채우려면 이전 코드를 루프에서 사용할 수 있습니다.

//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array

foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}

어레이 푸시 예제

public void ArrayPush<T>(ref T[] table, object value)
{
    Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
    table.SetValue(value, table.Length - 1); // Setting the value for the new element
}
int[] terms = new int[10]; //create 10 empty index in array terms

//fill value = 400 for every index (run) in the array
//terms.Length is the total length of the array, it is equal to 10 in this case 
for (int run = 0; run < terms.Length; run++) 
{
    terms[run] = 400;
}

//print value from each of the index
for (int run = 0; run < terms.Length; run++)
{
    Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
}

Console.ReadLine();

/*출력:

0: 의값 0 인덱: 400
의 값: 인의 1 값덱: 400
2의 값: 지 2 값: 400
3 3:400
4 4:400
5 5:400
의 값: 지 6 값 : 400
7 7:400
8 8:400
9 9:400
*/

배열의 크기를 모르거나 추가하려는 기존 배열이 이미 있는 경우.두 가지 방법으로 진행할 수 있습니다.첫 번째는 제네릭을 사용하는 것입니다.List<T>을 이위배다을변로환합니다으음으로 해야 합니다.var termsList = terms.ToList();추가 방법을 사용합니다.그런 다음 작업이 완료되면 다음을 사용합니다.var terms = termsList.ToArray();배열로 다시 변환하는 방법입니다.

var terms = default(int[]);
var termsList = terms == null ? new List<int>() : terms.ToList();

for(var i = 0; i < 400; i++)
    termsList.Add(i);

terms = termsList.ToArray();

두 번째 방법은 현재 배열의 크기를 조정하는 것입니다.

var terms = default(int[]);

for(var i = 0; i < 400; i++)
{
    if(terms == null)
        terms = new int[1];
    else    
        Array.Resize<int>(ref terms, terms.Length + 1);
    
    terms[terms.Length - 1] = i;
}

. 3 .NET 3.5를Array.Add(...);

이 두 가지를 모두 사용하면 동적으로 작업을 수행할 수 있습니다. 항목을 이라면, 만당신많항추것가이면라요할그세사냥, ▁a▁use요▁if▁then세하▁lots사,▁just를 사용하세요.List<T>몇 가지 항목만 사용하는 경우 어레이 크기를 조정하는 것이 성능이 향상됩니다.이것은 당신이 그것을 만들기 위해 더 많은 히트를 치기 때문입니다.List<T>물건.

시대 눈금 단위:

3개의 아이템

배열 크기 조정 시간: 6

목록 추가 시간: 16

400개 항목

배열 크기 조정 시간: 305

목록 추가 시간: 20

저는 이것을 다른 변형에 추가하겠습니다.저는 이런 종류의 기능성 코딩 라인을 더 선호합니다.

Enumerable.Range(0, 400).Select(x => x).ToArray();

당신은 이것을 직접 할 수 없습니다.그러나 Linkq를 사용하여 다음 작업을 수행할 수 있습니다.

List<int> termsLst=new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsLst.Add(runs);
}
int[] terms = termsLst.ToArray();

처음에 배열 용어가 비어 있지 않은 경우 먼저 목록으로 변환한 다음 작업을 수행할 수 있습니다.예:

    List<int> termsLst = terms.ToList();
    for (int runs = 0; runs < 400; runs++)
    {
        termsLst.Add(runs);
    }
    terms = termsLst.ToArray();

참고: '시스템 사용'을 추가하는 것을 잊지 마십시오.파일의 시작 부분에 'Linq;'가 있습니다.

이것은 나에게 훨씬 덜 문제가 되는 것처럼 보입니다.

var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();

다른 접근 방식:

int runs = 0; 
bool batting = true; 
string scorecard;

while (batting = runs < 400)
    scorecard += "!" + runs++;

return scorecard.Split("!");
int[] terms = new int[400];

for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}
         static void Main(string[] args)
        {
            int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/
            int i, j;


          /*initialize elements of array arrayname*/
            for (i = 0; i < 5; i++)
            {
                arrayname[i] = i + 100;
            }

             /*output each array element value*/
            for (j = 0; j < 5; j++)
            {
                Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]);
            }
            Console.ReadKey();/*Obtains the next character or function key pressed by the user.
                                The pressed key is displayed in the console window.*/
        }
            /*arrayname is an array of 5 integer*/
            int[] arrayname = new int[5];
            int i, j;
            /*initialize elements of array arrayname*/
            for (i = 0; i < 5; i++)
            {
                arrayname[i] = i + 100;
            }

ToArray() 메서드를 사용하지 않고 C#을 사용하여 문자열 배열에 목록 값을 추가하려면 다음과 같이 하십시오.

        List<string> list = new List<string>();
        list.Add("one");
        list.Add("two");
        list.Add("three");
        list.Add("four");
        list.Add("five");
        string[] values = new string[list.Count];//assigning the count for array
        for(int i=0;i<list.Count;i++)
        {
            values[i] = list[i].ToString();
        }

값 배열의 출력에는 다음이 포함됩니다.

하나.

두명

세개

네개

다섯개

목록을 사용하여 이 작업을 수행할 수 있습니다.방법은 이렇습니다

List<string> info = new List<string>();
info.Add("finally worked");

그리고 이 배열을 반환해야 할 경우에는

return info.ToArray();

다음은 새로운 숫자와 문자열을 추가하는 방법 중 하나입니다.Array:

int[] ids = new int[10];
ids[0] = 1;
string[] names = new string[10];

do
{
    for (int i = 0; i < names.Length; i++)
    {
        Console.WriteLine("Enter Name");
        names[i] = Convert.ToString(Console.ReadLine());
        Console.WriteLine($"The Name is: {names[i]}");
        Console.WriteLine($"the index of name is: {i}");
        Console.WriteLine("Enter ID");
        ids[i] = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine($"The number is: {ids[i]}");
        Console.WriteLine($"the index is: {i}");
    }


} while (names.Length <= 10);

언급URL : https://stackoverflow.com/questions/202813/adding-values-to-a-c-sharp-array

반응형