Conversão do System.Array para List


279

Ontem à noite, sonhei que o seguinte era impossível. Mas, no mesmo sonho, alguém da SO me disse o contrário. Por isso, gostaria de saber se é possível converter System.ArrayparaList

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);

para

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

2
Abaixo o link mostra como funciona no c # codegateway.com/2011/12/…

6
Você deve converter o Arrayque realmente é, e int[], em seguida, pode usar ToList:((int[])ints).ToList();
Tim Schmelter 4/15/16

Respostas:


428

Salve-se um pouco de dor ...

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.

Também pode apenas ...

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

ou...

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

ou...

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

ou...

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

15
Nota para conclusão: o segundo método está disponível apenas em C # 3.0+.
21910 Jon Seigel

21
Como a matriz int já é implementada IEnumerable<int>, isso OfType<int>()não é necessário. ints.ToList();é suficiente.
Heinzi

16
Para OfType, você precisa System.Linq
JasonPlutext

11
Nenhum desses exemplos realmente responde à pergunta real. Mas acho que ele aceitou a resposta e ficou feliz. Ainda assim, nenhum deles realmente converte uma matriz em uma lista. "Conversão do System.Array para lista". Deve-se adicionar esse exemplo para completar a IMO. (Resposta Ser superior e todos)
Søren Ullidtz

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

84

Há também uma sobrecarga de construtores para a List que funcionará ... Mas acho que isso exigiria uma matriz tipada forte.

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

... para classe Array

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);

Entre essa abordagem e a ToList()que está usando , qual é mais eficiente? Ou existe alguma diferença?
Ben Sutton

1
Difícil dizer sem saber o tamanho real do conjunto de dados (a lista usa internamente matrizes que devem poder ser expandidas. As matrizes são imutáveis.) Se você souber o tamanho da lista antecipadamente dessa maneira, poderá melhorar um pouco o desempenho ... mas o ganho será tão pequeno que você Você também pode usar a versão que prefere manter.
Matthew Whited

3
Você já reparou que este tópico tem 6 anos? (E minha segunda resposta lida directamente a exemplo do uso Arrayem vez de int[].)
Matthew Whited

66

Curiosamente, ninguém responde à pergunta, o OP não está usando um tipo fortemente digitado, int[]mas um Array.

Você precisa converter o Arrayque realmente é, an int[], e pode usar ToList:

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

Observe que Enumerable.ToListchama o construtor da lista que primeiro verifica se o argumento pode ser convertido ICollection<T>( para o qual uma matriz implementa); então, ele usará o ICollection<T>.CopyTométodo mais eficiente em vez de enumerar a sequência.


11
Obrigado, Enum.GetValuesretorna uma matriz e isso me ajudou a fazer uma lista com ela.
Martin Braun

3
Eu sei que isso é antigo, mas você está certo, a pergunta é respondida por isso. Na minha situação, um desserializador dinâmico retorna uma matriz do sistema porque precisa estar preparada para aceitar qualquer tipo de tipo de dados, para que você não possa pré-carregar a lista até o tempo de execução. Obrigado
Frank Cedeno 2/17

27

O método mais simples é:

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

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

ou

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

7
Uma das necessidades using System.Linq;para ToList()o trabalho.
Jarekczek

Isso não funciona Array. Você precisa transmiti-lo ou ligar .Cast<>primeiro.
BlueRaja - Danny Pflughoeft

11

No caso de você desejar retornar uma matriz de enumerações como uma lista, você pode fazer o seguinte.

using System.Linq;

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

5

Você pode fazer assim basicamente:

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

este é o seu array e você pode chamar sua nova lista assim:

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

Você também pode fazer isso para objetos complexos.


4

em vb.net basta fazer isso

mylist.addrange(intsArray)

ou

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

2
muito melhor do que usar OfType <> (meu VS2010 não iria aceitar nada OfType ...)
woohoo

3

Você pode tentar o seu código:

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;

Então você pode simplesmente usar o anyVariable como seu código.


2

Basta usar o método existente. .ToList ();

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

BEIJO (MANTÊ-LO SENHOR SIMPLES)


0

Espero que isto seja útil.

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

obter valor da string

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);

obter valor inteiro

        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);
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.