Conversion from List to array T[]

后端 未结 7 917
一向
一向 2020-11-27 18:28

Is there a short way of converting a strongly typed List to an Array of the same type, e.g.: List to MyClass[]

相关标签:
7条回答
  • 2020-11-27 19:01

    You can simply use ToArray() extension method

    Example:

    Person p1 = new Person() { Name = "Person 1", Age = 27 };
    Person p2 = new Person() { Name = "Person 2", Age = 31 };
    
    List<Person> people = new List<Person> { p1, p2 };
    
    var array = people.ToArray();
    

    According to Docs

    The elements are copied using Array.Copy(), which is an O(n) operation, where n is Count.

    0 讨论(0)
提交回复
热议问题