简体   繁体   中英

Convert List<T> to Array in C#

I have a list derived from

public class main
{
     public list<myclass> data  { get; set; }
}

 public class myclass
    {
        public string variety { get; set; }
        public string ordertype { get; set; }
        public string producttype { get; set; }
    }

Now I want to convert the List to return an array for VBA interop, how can I loop through my class in a single statement to convert all elements to array in one go. I have a few other classes that have a huge number of elements. I've tried the below code, but it's throwing out of bound error. I need to automatically loop through elements in myclass and assign it to array and so on. Is there any alternative/one-liner statement for this to convert the entire list to array.

string[] NamesArray = new string[list.Count];
string[] NamesArray2 = new string[] { };
for (int i = 0; i < NamesArray.Length; i++)
{
 int idx = 0;
 NamesArray[i] = bres.data[i].ToString();//here I am getting the myclass list not the elements inside the myclass.
foreach (var k in NamesArray[i].)
  {
     NamesArray2[idx++] = k.value.ToString();
  }
 }

Why don't you try doing:

myclass[] arr = data.ToArray();

Edit: To return the array so it's visible from VBA, you'd need to have your class as ComVisible.

[ComVisible(true)]
public class main
{
    public list<myclass> data  { get; set; }
}
[ComVisible(true)]
public class myclass
{
    public string variety { get; set; }
    public string ordertype { get; set; }
    public string producttype { get; set; }
}
[ComVisible(true)]
public myclass[] myclasses()
{
     myclass[] arr = data.ToArray();
     return arr;
}

@freeflow has a great reference link that you can use: https://analystcave.com/excel-use-c-sharp-in-excel-vba/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM