c#如何将stringp[] 转换为list<string>?
时间: 2023-11-10 08:51:57 浏览: 36
你可以使用`ToList()`方法来将一个`string[]`数组转换为`List<string>`列表。下面是一个示例代码:
```csharp
string[] stringArray = new string[] { "apple", "banana", "cherry" };
List<string> stringList = stringArray.ToList();
```
在上述代码中,`stringArray`是一个`string[]`数组,`stringList`是一个`List<string>`列表。通过调用`ToList()`方法将数组转换为列表。
希望对你有所帮助!如果还有其他问题,请随时提问。
相关问题
C# String 分隔符 转 list
以下是两种C#将字符串分隔符转为列表的方法:
1. 使用Split方法和foreach循环:
```csharp
string str = "a a a a a\n b b b b b\n";
string[] liststr = str.Split('\n');
List<string> mylist = new List<string>();
foreach (var item in liststr)
{
mylist.Add(item);
}
Console.Write(mylist.Count); // 输出:2
Console.Write(mylist[1]); // 输出: b b b b b
```
2. 使用ToCharArray方法和Split方法:
```csharp
string str1 = "a a a a a\n b b b b b\n";
char[] p = str1.ToCharArray();
Console.WriteLine("data char length:" + p.Length);
string[] liststr1 = str1.Split(p[0]);
List<string> mydata = new List<string>();
foreach (var item in liststr1)
{
mydata.Add(item);
}
```
C#数组,List,Dictionary的相互转换
在C#中,数组、List和Dictionary是常见的数据结构。下面介绍它们之间的相互转换方法。
1. 数组转List
```csharp
int[] arr = { 1, 2, 3 };
List<int> list = arr.ToList();
```
2. List转数组
```csharp
List<int> list = new List<int>() { 1, 2, 3 };
int[] arr = list.ToArray();
```
3. 数组转Dictionary
```csharp
string[] arr = { "a", "b", "c" };
Dictionary<int, string> dict = arr.Select((s, i) => new { Key = i, Value = s }).ToDictionary(p => p.Key, p => p.Value);
```
4. List转Dictionary
```csharp
List<string> list = new List<string>() { "a", "b", "c" };
Dictionary<int, string> dict = list.Select((s, i) => new { Key = i, Value = s }).ToDictionary(p => p.Key, p => p.Value);
```
5. Dictionary转数组
```csharp
Dictionary<int, string> dict = new Dictionary<int, string>() { { 0, "a" }, { 1, "b" }, { 2, "c" } };
string[] arr = dict.Values.ToArray();
```
6. Dictionary转List
```csharp
Dictionary<int, string> dict = new Dictionary<int, string>() { { 0, "a" }, { 1, "b" }, { 2, "c" } };
List<string> list = dict.Values.ToList();
```