在多个数组中分割字符串的最佳方法是什么?

本文关键字:最佳 方法 是什么 字符串 分割 数组 | 更新日期: 2023-09-27 18:16:12

我使用WebRequestMethods.Ftp.ListDirectoryDetails方法从FTP服务器获取文件。

字符串格式为:11-02-16 11:33AM abc.xml'r'n11-02-16 11:35AM xyz.xml
我能够将11-02-16 11:33AM abc.xml存储在数组中。

如何在数组中存储日期和文件名

我不想枚举整个数组并再次拆分每个值

在多个数组中分割字符串的最佳方法是什么?

我建议使用Dictionary<DateTime, string>;

List<string> splits = "yourSplitsStringArray".ToList();
//Create your Result Dictionary
Dictionary<DateTime, string> result = new Dictionary<DateTime, string>();
//Process your data:
splits.ForEach(x => result.Add(DateTime.Parse(x.Substring(0, 16)), x.Substring(17, x.Length - 17)));

关于你的字符串:

|0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|
|1|1|-|0|2|-|1|6| |1| 1| :| 3| 3| A| M| a| b| c| .| x| m| l|

那么你的DateTime从[0]开始,总长度为16 => x.Substring(0, 16)

您的文件名以[17]开头,长度为x.Lenght - 17字符。

我知道你不想再列举一遍,但我认为这是实现你所需要的最简单、最实用的方法。

你也可以在你的第一个分割操作中包含我的部分答案。

但是:

因为它是一个字典DateTime必须是唯一的。所以,如果你不确定是否会是这种情况,使用List<Tuple<DateTime, string>>代替。它类似于字典。

这将改变你的Linq为:

//Process your data:
splits.ForEach(x => result.Add(new Tuple<DateTime, string>(DateTime.Parse(x.Substring(0, 16)), x.Substring(17, x.Length - 17))));