I have a dynamic string:
我有一个动态字符串:
It looks like "1: Name, 2: Another Name"
this. I want to split it and convert it to a List<KeyValuePair<int, string>>
or IEnmerable<KeyValuePair<int, string>>
它看起来像“1:名字,2:另一个名字”。我想拆分它并将其转换为List
I tried this.
我试过这个。
myString.Split(',').Select(s => s => new KeyValuePair<int, string>( Convert.ToInt32(s.Substring(s.LastIndexOf(':'), s.Substring(0, s.LastIndexOf(':')) + 1))))
Does not to help much. I can do strings of Dictionary or a foreach or a for loop. I rather do it as a key value pair lambda expression one liner.
没有多大帮助。我可以做Dictionary或foreach或for循环的字符串。我宁愿做一个关键值对lambda表达式一个衬垫。
4 个解决方案
#1
1
Try this:
尝试这个:
myString.Split(',').Select(s => new KeyValuePair<int, string>(
int.Parse(s.Split(':').GetValue(0).ToString()),
s.Split(':').GetValue(1).ToString()
));
#2
1
You need to split twice first by comma, then by colon. Try this code:
您需要先用逗号分割两次,然后用冒号分割。试试这段代码:
var input = "1: Name, 2: Another Name";
var list = input.Split(',')
.Select(p =>
{
var kv = p.Split(':');
return new KeyValuePair<int, string>(int.Parse(kv[0].Trim()), kv[1]);
})
.ToList();
#3
1
One-liner:
一内胆:
WARNING: No exception handling
警告:无异常处理
myString.Split(',').Select(x => new KeyValuePair<int, string>(int.Parse(x.Split(':')[0]), x.Split(':')[1]))
#4
0
Another way to achieve that with the beauty of regex:
用正则表达式之美来实现这一目标的另一种方法:
var result = new List<KeyValuePair<int, string>>();
foreach (Match match in Regex.Matches("1: Name, 2: Another Name", @"((\d+): ([\w ]+))"))
{
result.Add(new KeyValuePair<int, string>(int.Parse(match.Groups[2].Value), match.Groups[3].Value));
}
#1
1
Try this:
尝试这个:
myString.Split(',').Select(s => new KeyValuePair<int, string>(
int.Parse(s.Split(':').GetValue(0).ToString()),
s.Split(':').GetValue(1).ToString()
));
#2
1
You need to split twice first by comma, then by colon. Try this code:
您需要先用逗号分割两次,然后用冒号分割。试试这段代码:
var input = "1: Name, 2: Another Name";
var list = input.Split(',')
.Select(p =>
{
var kv = p.Split(':');
return new KeyValuePair<int, string>(int.Parse(kv[0].Trim()), kv[1]);
})
.ToList();
#3
1
One-liner:
一内胆:
WARNING: No exception handling
警告:无异常处理
myString.Split(',').Select(x => new KeyValuePair<int, string>(int.Parse(x.Split(':')[0]), x.Split(':')[1]))
#4
0
Another way to achieve that with the beauty of regex:
用正则表达式之美来实现这一目标的另一种方法:
var result = new List<KeyValuePair<int, string>>();
foreach (Match match in Regex.Matches("1: Name, 2: Another Name", @"((\d+): ([\w ]+))"))
{
result.Add(new KeyValuePair<int, string>(int.Parse(match.Groups[2].Value), match.Groups[3].Value));
}