在 C# 中将列表<T> 转换为数组

Convert List<T> to Array in C#

我有一个列表来自

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

现在我想将列表转换为 return 一个用于 VBA 互操作的数组,我如何在单个语句中遍历我的 class 以将所有元素转换为数组一去。我还有一些其他 classes 有大量的元素。我已经尝试了下面的代码,但它抛出了越界错误。我需要自动循环遍历 myclass 中的元素并将其分配给数组等。是否有任何 alternative/one-liner 语句将整个列表转换为数组。

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

你为什么不尝试做:

myclass[] arr = data.ToArray();

编辑: 要 return 数组以便它在 VBA 中可见,您需要将 class 作为 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 有一个很好的参考 link,您可以使用:https://analystcave.com/excel-use-c-sharp-in-excel-vba/