System.Array를 목록으로 변환


279

어제 밤 나는 다음이 불가능하다는 꿈을 꾸었다. 그러나 같은 꿈에서 SO의 누군가가 다르게 말해주었습니다. 따라서 변환 System.Array이 가능한지 알고 싶습니다.List

Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);
ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);

List<int> lst = ints.OfType<int>(); // not working

2
아래 링크는 C # codegateway.com/2011/12/…

6
당신은 Array그것이 실제로 무엇인지 에 캐스팅해야 하며 int[], 다음을 사용할 수 있습니다 ToList:((int[])ints).ToList();
Tim Schmelter

답변:


428

고통을 덜고 ...

using System.Linq;

int[] ints = new [] { 10, 20, 10, 34, 113 };

List<int> lst = ints.OfType<int>().ToList(); // this isn't going to be fast.

그냥 ...

List<int> lst = new List<int> { 10, 20, 10, 34, 113 };

또는...

List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);

또는...

List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });

또는...

var lst = new List<int>();
lst.AddRange(new int[] { 10, 20, 10, 34, 113 });

15
완전성 참고 : 두 번째 방법은 C # 3.0 이상에서만 사용할 수 있습니다.
Jon Seigel

21
int 배열 이미 구현 이후 IEnumerable<int>의는 OfType<int>()필요하지 않습니다. ints.ToList();충분하다.
Heinzi

16
OfType의 경우 System.Linq
JasonPlutext

11
이 예제들 중 어느 것도 실제로 실제 질문에 대답하지 않습니다. 그러나 나는 그가 대답을 받아 들여서 행복했다고 생각합니다. 여전히 이들 중 하나가 실제로 배열을 목록으로 변환하지는 않습니다. "System.Array를 목록으로 변환". 완전성 IMO에 대한 예제를 추가해야합니다. (최고의 답변이 됨)
Søren Ullidtz

4
Enum.GetValues ​​(typeof (Enumtype)). Cast <itemtype> (). ToList ()
Phan Đức Bình

84

작동하는 List의 생성자 오버로드도 있습니다 ...하지만 강력한 형식의 배열이 필요할 것 같습니다.

//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);

... 배열 클래스

var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
    intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);

이 방법과을 사용하는 방법 중 ToList()어느 것이 더 효율적입니까? 아니면 차이가 있습니까?
벤 서튼

1
실제 데이터 세트 크기를 모르면 말하기 어렵습니다 (List는 내부적으로 확장 할 수있는 배열을 사용합니다. 배열은 불변입니다.)이 방법으로 List 크기를 미리 알고 있으면 성능이 약간 향상 될 수 있지만 이득은 너무 작아집니다. 유지하려는 버전을 사용할 수도 있습니다.
Matthew Whited

3
이 글타래가 6 살짜리라는 것을 눈치 채 셨나요? (그리고 두 번째 답변 Arrayint[]. 대신에 그의 사용 예제를 직접 처리합니다 .)
Matthew Whited

66

흥미롭게도 아무 대답 질문, 영업 이익은 강력한 형식의 사용하지 않는 int[]하지만를 Array.

당신은 Array실제로 그것이 무엇인지 캐스팅해야 하며 int[], 다음을 사용할 수 있습니다 ToList:

List<int> intList = ((int[])ints).ToList();

인수가 캐스트 될 수 있는지 (배열이 구현할 수 있는지) 먼저 확인 Enumerable.ToList하는 목록 생성자 를 호출 하면 시퀀스를 열거하는 대신 ICollection<T>보다 효율적인 ICollection<T>.CopyTo메소드 를 사용합니다 .


11
감사 Enum.GetValues합니다. Array를 반환하면 목록에서 목록을 만들 수 있습니다.
Martin Braun

3
나는 이것이 오래된 것을 알고 있지만 당신이 옳습니다. 질문은 이것에 의한 대답입니다. 내 상황에서 동적 deserializer는 시스템 배열을 반환합니다. 시스템 배열은 모든 종류의 데이터 유형을 받아 들일 준비가되어있어 런타임까지 목록을 미리로드 할 수 없기 때문입니다. 감사합니다
Frank Cedeno

27

가장 간단한 방법은 다음과 같습니다.

int[] ints = new [] { 10, 20, 10, 34, 113 };

List<int> lst = ints.ToList();

또는

List<int> lst = new List<int>();
lst.AddRange(ints);

7
하나는 필요 using System.Linq;를 위해 ToList()일한다.
Jarekczek

이 기능은 작동하지 않습니다 Array. 당신은 그것을 캐스팅하거나 .Cast<>먼저 전화해야합니다 .
BlueRaja-

11

열거 형 배열을 목록으로 반환하려는 경우 다음을 수행 할 수 있습니다.

using System.Linq;

public List<DayOfWeek> DaysOfWeek
{
  get
  {
    return Enum.GetValues(typeof(DayOfWeek))
               .OfType<DayOfWeek>()
               .ToList();
  }
}

5

기본적으로 다음과 같이 할 수 있습니다.

int[] ints = new[] { 10, 20, 10, 34, 113 };

이것은 배열이며 다음과 같이 새 목록을 호출 할 수 있습니다.

 var newList = new List<int>(ints);

복잡한 객체에 대해서도이 작업을 수행 할 수 있습니다.


4

vb.net 에서이 작업을 수행하십시오.

mylist.addrange(intsArray)

또는

Dim mylist As New List(Of Integer)(intsArray)

2
OfType <>을 사용하는 것보다 훨씬 낫다 (내 VS2010은 OfType을 받아들이지 않을 것이다 ...)
woohoo

3

코드에 시도해 볼 수 있습니다.

Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);

ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);

int[] anyVariable=(int[])ints;

그런 다음 anyVariable을 코드로 사용할 수 있습니다.


2

기존 방법을 사용하십시오. .ToList ();

   List<int> listArray = array.ToList();

키스 (간단히 유지)


0

도움이 되길 바랍니다.

enum TESTENUM
    {
        T1 = 0,
        T2 = 1,
        T3 = 2,
        T4 = 3
    }

문자열 값을 얻습니다

string enumValueString = "T1";

        List<string> stringValueList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m => 
            Convert.ToString(m)
            ).ToList();

        if(!stringValueList.Exists(m => m == enumValueString))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertString;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertString);

정수 값을 얻다

        int enumValueInt = 1;

        List<int> enumValueIntList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
            Convert.ToInt32(m)
            ).ToList();

        if(!enumValueIntList.Exists(m => m == enumValueInt))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertInt;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertInt);
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.