欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中List〈string〉和string[]数组之间的相互转换

程序员文章站 2023-12-10 22:37:16
1,从system.string[]转到list system.string[] str={"str","string","ab...

1,从system.string[]转到list<system.string>

system.string[] str={"str","string","abc"};

list<system.string> lists=new list<system.string>(str);

 

2, 从list<system.string>转到system.string[]

list<system.string> lists=new list<system.string>();

lists.add("str");

lists.add("hello");

system.string[] str=lists.toarray();

 

测试如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace consoleapplication1
{
    class program
    {
        static void main(string[] args)
        {
            system.string[] sa = { "str","string1","sting2","abc"};
            list<system.string> sl = new list<system.string>();
            for (system.int32 i = 0; i < sa.length;i++ )
            {
                console.writeline("sa[{0}]={1}",i,sa[i]);
            }
            sl = new list<system.string>(sa);
            sl.add("hello!");
            foreach(system.string s in sl)
            {
                console.writeline(s);
            }
            system.string[] nextstring = sl.toarray();
            console.writeline("the length of nextstring is {0}",nextstring.length);
            console.read();
        }
    }
}

结果显示:

C#中List〈string〉和string[]数组之间的相互转换