我有一个字符串Number1.pdf:Alpha1.pdf; Number2.pdf:Alpha2.pdf; Number3.pdf:Alpha3.pdf;
,我想把它转换成字典。
Ditionary<Number1,Alpha1> etc.
我在网上查找示例,发现其中大多数将 Dictionary 转换为 String。有人可以帮我吗?
我会选择 LINQ:
var input = "Number1.pdf:Alpha1.pdf; Number2.pdf:Alpha2.pdf; Number3.pdf:Alpha3.pdf;";
var items = input.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var result = items.Select(x => x.Split(':'))
.ToDictionary(x => x[0].Split('.').First().Trim(),
x => x[1].Split('.').First().Trim());
它将.pdf
在键和值的末尾跳过(如问题所述)。
foreach (var i in result)
Console.WriteLine(i);
印刷
[Number1, Alpha1]
[Number2, Alpha2]
[Number3, Alpha3]
string s = "Number1.pdf:Alpha1.pdf; Number2.pdf:Alpha2.pdf; Number3.pdf:Alpha3.pdf;";
var names = s.Replace(".pdf","")
.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(':'))
.ToDictionary(x => x[0].Trim(), x => x[1]);