I'm new to C#, and thus am looking for layman's terms regarding this. Essentially, what I would like to do is turn:
我是C#的新手,因此我正在寻找外行人的条款。基本上,我想做的是转:
key1=val1|key2=val2|...|keyN=valN
键1 = VAL1 |键2 =值2 | ... | keyN = VALN
into a database array where, you guessed it, key1 returns val1, key2 returns val2, etc. I know I could return a string using split, but from that point on, I'm at a loss. Any help would be greatly appreciated! I hope I've made my intentions clear, but if you have any questions, don't hesitate to ask!
进入一个数据库数组,你猜对了,key1返回val1,key2返回val2等等。我知道我可以使用split返回一个字符串,但从那时起,我不知所措。任何帮助将不胜感激!我希望我的意图明确,但如果您有任何疑问,请不要犹豫!
3 个解决方案
#1
50
string s = "key1=val1|key2=val2|keyN=valN";
var dict = s.Split('|')
.Select(x => x.Split('='))
.ToDictionary(x => x[0], x => x[1]);
Now dict
is a Dictionary<string, string>
with the desired key/value pairs.
现在dict是一个Dictionary
#2
8
Dictionary<string,string> results = new Dictionary<string,string>();
foreach(string kvp in source.split('|'))
{
results.Add(kvp.split('=')[0], kvp.split('=')[1]);
}
Probably a Linq way of doing it.
可能是Linq这样做的方式。
#3
3
string s = "key1=val1|key2=val2|keyN=valN";
var dict = s.Split('|')
.Select(x => x.Split('='))
.Where(x => x.Length > 1 && !String.IsNullOrEmpty(x[0].Trim())
&& !String.IsNullOrEmpty(x[1].Trim()))
.ToDictionary(x => x[0].Trim(), x => x[1].Trim());
#1
50
string s = "key1=val1|key2=val2|keyN=valN";
var dict = s.Split('|')
.Select(x => x.Split('='))
.ToDictionary(x => x[0], x => x[1]);
Now dict
is a Dictionary<string, string>
with the desired key/value pairs.
现在dict是一个Dictionary
#2
8
Dictionary<string,string> results = new Dictionary<string,string>();
foreach(string kvp in source.split('|'))
{
results.Add(kvp.split('=')[0], kvp.split('=')[1]);
}
Probably a Linq way of doing it.
可能是Linq这样做的方式。
#3
3
string s = "key1=val1|key2=val2|keyN=valN";
var dict = s.Split('|')
.Select(x => x.Split('='))
.Where(x => x.Length > 1 && !String.IsNullOrEmpty(x[0].Trim())
&& !String.IsNullOrEmpty(x[1].Trim()))
.ToDictionary(x => x[0].Trim(), x => x[1].Trim());