IT

c # .net의 기존 배열에 새 항목 추가

lottoking 2020. 7. 11. 09:20
반응형

c # .net의 기존 배열에 새 항목 추가


C # .net의 기존 배열에 새 항목을 추가하는 방법은 무엇입니까?

기존 데이터를 보존해야합니다.


동적 크기의 배열이 필요한 경우 목록을 사용합니다.

List<string> ls = new List<string>();
ls.Add("Hello");

그것은 해결책이 될 수 있습니다.

Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"

그러나 동적 크기 배열의 경우 목록도 선호합니다.


LINQ 사용 :

arr = (arr ?? Enumerable.Empty<string>()).Concat(new[] { newitem }).ToArray();

나는 사용하는 것을 좋아하며 스위치 문, 간단한 경우 문에 포함하거나 인수로 전달하는 것이 매우 편리합니다.

편집하다 :

일부 사람들은 new[] { newitem }작은 한 항목의 임시 배열을 만들기 때문에 싫어 합니다. 다음은 Enumerable.Repeat졸업을 만들 필요가없는 버전 입니다 (적어도 표면에는 없습니다 ..

arr = (arr ?? Enumerable.Empty<string>()).Concat(Enumerable.Repeat(newitem,1)).ToArray();

그리고 배열이 null시작 되지 않는 것이 확실하다면 다음과 같이 단순화 할 수 있습니다.

arr.Concat(Enumerable.Repeat(newitem,1)).ToArray();

정렬 된 컬렉션에 항목을 추가하려는 경우 List, 배열이 아닌 원하는 데이터 구조 일 수 있습니다.


C #에서 배열은 불변 예를 들어 string[], int[]. 즉, 크기를 수 없습니다. 새로운 배열을 제거합니다.

다음은 Array.Resize 의 코드입니다 .

public static void Resize<T>(ref T[] array, int newSize)
{
    if (newSize < 0)
    {
        throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
    }
    T[] sourceArray = array;
    if (sourceArray == null)
    {
        array = new T[newSize];
    }
    else if (sourceArray.Length != newSize)
    {
        T[] destinationArray = new T[newSize];
        Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length > newSize) ? newSize : sourceArray.Length);
        array = destinationArray;
    }
}

보시다시피 새로운 크기의 새 배열을 만들고 소스 배열의 내용을 복사하고 참조를 새 배열로 설정합니다. 이에 대한 힌트 는 첫 번째 번째 변수 ref 키워드입니다.

새 항목에 새 슬롯동적으로 할당 할 수있는 목록이 있습니다 . 예를 들어 목록 <T> 입니다. 이것들은 불변 배열을 포함하고 필요할 때 크기를 조정합니다 (List <T>는 사용 목록 구현이 아닙니다!). ArrayList 는 Generics가없는 것과 동일합니다 ( Object 배열 사용).

LinkedList <T> 는 실제 연결 목록 구현입니다. 불행히도 LinkListNode <T> 요소 만 목록에 추가 할 수 있으므로 고유 한 목록 요소를이 노드 유형으로 랩핑해야합니다. 나는 그것의 사용이 드물다고 생각합니다.


아주 오래된 질문이지만 여전히 추가하고 싶었습니다.

하나의 라이너를 보유하고있는 권한 아래 코드를 사용할 수 있습니다. 열거 형과 "신규"(질문이 제기 된 이후) 이니셜 라이저 구문을 허용하는 목록 생성 결합합니다.

myArray = new List<string>(myArray) { "add this" }.ToArray();

 Array.Resize(ref youur_array_name, your_array_name.Length + 1);
 your_array_name[your_array_name.Length - 1] = "new item";

@Stephen Chung이 제공하는 답변을 LINQ 기반 논리를 사용하여 일반 유형을 사용하여 확장 방법을 만들 수 있습니다.

public static class CollectionHelper
{
    public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item)
    {
        return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item });
    }

    public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
    {
        return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();
    }

    public static T[] AddToArray<T>(this T[] sequence, T item)
    {
        return Add(sequence, item).ToArray();
    }

}

그런 다음 이와 같이 배열에서 직접 호출 할 수 있습니다.

    public void AddToArray(string[] options)
    {
        // Add one item
        options = options.AddToArray("New Item");

        // Add a 
        options = options.AddRangeToArray(new string[] { "one", "two", "three" });

        // Do stuff...
    }

명백히, AddRangeToArray () 메소드는 Concat ()과 동일한 기능을 가지고 있기 때문에 약간 과잉 인 것처럼 보이지만, 이렇게하면 최종 코드가 이것과 배열에서 직접 "작동"할 수 있습니다.

options = options.Concat(new string[] { "one", "two", "three" }).ToArray();

배열로 많은 작업을 수행하고 어떤 MIS 목록을 작성 될지 말이 일반 유형의 일반 메소드 Add가 도움이 수 있습니다.

    public static T[] Add<T>(T[] array, T item)
    {
        T[] returnarray = new T[array.Length + 1];
        for (int i = 0; i < array.Length; i++)
        {
            returnarray[i] = array[i];
        }
        returnarray[array.Length] = item;
        return returnarray;
    }

배열을 변경 불가능하고 고정 된 크기로 유지하는 것이 좋습니다.

시뮬레이션 할 당신이 수 AddExtension MethodIEnumerable.Concat()

public static class ArrayExtensions
    {
        public static string[] Add(this string[] array, string item)
        {
            return array.Concat(new[] {item}).ToArray();
        }
    }

제안 된 모든 답변은 피하고 싶은 것과 동일하게 수행하여 새 어레이를 만들고 더 많은 오버를 잃어 버리고 새 항목을 추가합니다. LINQ는 마법이 아닙니다. T 목록은 항목이 추가 될 때 내부 배열의 크기를 조정하지 않도록 추가 공간이있는 버퍼 공간이있는 배열입니다.

모든 추상화는 동일한 문제를 해결하고 값을 보유하고 반환하는 빈 배치가없는 배열을해야합니다.

유연성이 필요한 경우 통과하는 데 사용할 수있는 충분히 큰 목록을 만들 수 있습니다. 배열을 사용하고 배열을 공유합니다. 또한 새로운 Span은 목록을 복사하지 않는 데이터를 공유하는 데 도움이됩니다.

질문에 답 :

Array.Resize(ref myArray, myArray.Length + 1);
data[myArray.Length - 1] = Value;

목록을 사용하는 것이 메모리 관리를위한 최선의 선택이 될 것입니다.


나는 Ed와 동의합니다. C #은 VB가 ReDim Preserve를 사용하는 것처럼 쉽게 만들지 만들었습니다. 컬렉션이 컬렉션 어레이를 더 큰 컬렉션에 복사해야합니다.


string str = "string ";
List<string> li_str = new List<string>();
    for (int k = 0; k < 100; i++ )
         li_str.Add(str+k.ToString());
string[] arr_str = li_str.ToArray();

확장 방법을 사용하는 것은 어떻습니까? 예를 들면 :

public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> source, TSource item)
{
    return source.Union(new TSource[] { item });
}

예를 들면 :

string[] sourceArray = new []
{
    "foo",
    "bar"
}
string additionalItem = "foobar";
string result = sourceArray.Union(additionalItem);

이 Linq의 Uniion 확장 (두 배열을 새 배열로 결합하는 데 사용됨)의 정상적인 동작을 모방하고 Linq 라이브러리가 작동해야합니다.


private static string[] GetMergedArray(string[] originalArray, string[] newArray)
    {
        int startIndexForNewArray = originalArray.Length;
        Array.Resize<string>(ref originalArray, originalArray.Length + newArray.Length);
        newArray.CopyTo(originalArray, startIndexForNewArray);
        return originalArray;
    }

Stringbuilder 클래스를 사용합니다 . .insert 및 .append와 같은 메소드가 있습니다. 여기에서 자세한 내용을 읽을 수 있습니다. http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx


불행히도 목록을 사용하는 것은 모든 상황에서 작동하지 않습니다. 목록과 배열은 실제로 다르며 100 % 상호 교환 할 수 없습니다. 허용 가능한 해결 방법인지 여부는 상황에 따라 상황에 따라 달라집니다.


이 질문은 답변에 만족하지 답변이 답변을 추가하고 싶습니다 :)

public class CustomArrayList<T> 
 {  
   private T[] arr;  private int count;  

public int Count  
  {   
    get   
      {    
        return this.count;   
      }  
   }  
 private const int INITIAL_CAPACITY = 4;  

 public CustomArrayList(int capacity = INITIAL_CAPACITY) 
 {  
    this.arr = new T[capacity];   this.count = 0; 
  } 

 public void Add(T item) 
  {  
    GrowIfArrIsFull();  
   this.arr[this.count] = item;  this.count++; 
  }  

public void Insert(int index, T item) 
{  
 if (index > this.count || index < 0)  
    {   
      throw new IndexOutOfRangeException(    "Invalid index: " + index);  
     }  
     GrowIfArrIsFull();  
     Array.Copy(this.arr, index,   this.arr, index + 1, this.count - index);          
    this.arr[index] = item;  this.count++; }  

    private void GrowIfArrIsFull() 
    {  
    if (this.count + 1 > this.arr.Length)  
    {   
      T[] extendedArr = new T[this.arr.Length * 2];  
      Array.Copy(this.arr, extendedArr, this.count);  
      this.arr = extendedArr;  
    } 
  }
 }
}

기존의 기존 어레이가있는 경우 빠른 수정은

var tempList = originalArray.ToList();
tempList.Add(newitem);

이제 원래 어레이를 새 어레이 교체하십시오.

originalArray = tempList.ToArray();

참고 URL : https://stackoverflow.com/questions/249452/add-new-item-in-existing-array-in-c-net

반응형