How to copy string of array to list<string>?

34,686

Pass string array in list constructor.

List<string> yourList = new List<string>(strArray);

The reason your first line didn't work was because you are not using the correct syntax. So instead of

List<string> lstArray  = strArray.toList<string>;

Use

List<string> lstArray = strArray.ToList<string>();

or

List<string> lstArray = strArray.ToList(); // with less keystrokes, since the array is of type string. 

For the 2nd option where you are trying to use Array.CopyTo, it works with array types, not generic list. You are probably getting the error.

The best overloaded method match for 'System.Array.CopyTo(System.Array, int)' has some invalid arguments

Since it expects an array and you are passing a generic list.

Share:
34,686
rangasathish
Author by

rangasathish

Updated on July 17, 2022

Comments

  • rangasathish
    rangasathish almost 2 years

    Possible Duplicate:
    Convert array of strings to List<string>

    I am new to C# How to copy entire string of array to List?

    i have tried this but i didn't get any solution.

     List<string> lstArray  = strArray.toList<string>;
    
        or           
     List<string> lstArray = new List<string>();
     strArray.copyTo(lstArray,0);
    
  • Anirudha
    Anirudha over 11 years
    you should ans y his solution didnt work
  • Habib
    Habib over 11 years
    @Fake.It.Til.U.Make.It, thanks, I was actually doing that :)
  • rangasathish
    rangasathish over 11 years
    thankQ for providing now it's works fine @Habib
  • Habib
    Habib over 11 years
    @rangasathish, you are welcome