1

我有一个字符串Number1.pdf:Alpha1.pdf; Number2.pdf:Alpha2.pdf; Number3.pdf:Alpha3.pdf;,我想把它转换成字典。

Ditionary<Number1,Alpha1> etc.

我在网上查找示例,发现其中大多数将 Dictionary 转换为 String。有人可以帮我吗?

4

2 回答 2

5

我会选择 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]
于 2013-09-09T20:07:00.563 回答
3
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]);
于 2013-09-09T20:04:44.620 回答