将冒号分隔的字符串转换为字典<string,string =“”> </string,>

时间:2013-09-09 20:01:25

标签: c# asp.net

我有一个字符串Number1.pdf:Alpha1.pdf; Number2.pdf:Alpha2.pdf; Number3.pdf:Alpha3.pdf;,我希望将其转换为字典。

Ditionary<Number1,Alpha1> etc.

我在网上搜索了一些例子,我发现他们中的大多数都将字典转换为字符串。有人可以帮助我吗?

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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]);