简体   繁体   English

转换列表<t>到 C# 中的数组</t>

[英]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.现在我想转换列表以返回 VBA 互操作的数组,我如何在一条语句中循环遍历我的 class 以将所有元素转换为一个 go 中的数组。我有一些其他类具有大量元素。 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.我需要自动循环遍历 myclass 中的元素并将其分配给数组等。 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.编辑:要返回数组以便从 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 has a great reference link that you can use: https://analystcave.com/excel-use-c-sharp-in-excel-vba/ @freeflow 有一个很好的参考链接,您可以使用: https://analystcave.com/excel-use-c-sharp-in-excel-vba/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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