使用一个连接的LINQ语句拆分字符串

时间:2013-02-03 11:33:16

标签: c# linq c#-4.0

我想知道我是否可以改变这一点:

"abc , 123; xyz, 100; go, 9; move, 50;"

进入这个:

{ { "abc", "123" } , { "xyz" , "100" } , { "go" , "9" } , { "move" , "50" } }

string[2]数组),带有一个长连接的LINQ语句?

编辑:

首选from-in-where-select语句系列

编辑2:

另外,还有一种方法可以将输入字符串转换为某种复合类型,如struct { string, int }或某些Tuple<string,int>数组吗?

像:

{
    new Tuple<string, int>() { "abc", 123 } ,
    new Tuple<string, int>() { "xyz" , 100 } ,
    new Tuple<string, int>() { "go" , 9 } ,
    new Tuple<string, int>() { "move" , 50 }
}

2 个答案:

答案 0 :(得分:2)

使用String.SplitString.Trim以及LINQ select

var result = (from keyValuePair in myString.Split(';')
              where keyValuePair.Trim() != ""
              select (from t in keyValuePair.Split(',')
                      select t.Trim()).ToArray()).ToArray();()

更新

拥有KeyValuePair<string, int>

的数组
var result = (from keyValuePair in myString.Split(';')
              where keyValuePair.Trim() != ""
              let splittedKeyValuePair = keyValuePair.Split(',')
              select new KeyValuePair<string, int>(splittedKeyValuePair[0].Trim(), int.Parse(splittedKeyValuePair[1]))).ToArray();

拥有Dictionary<string, int>

var result = (from keyValuePair in myString.Split(';')
              where keyValuePair.Trim() != ""
              select keyValuePair.Split(',')).ToDictionary(kvp => kvp[0].Trim(), kvp => int.Parse(kvp[1]))

答案 1 :(得分:1)

试试这个:

string str = "abc , 123; xyz, 100; go, 9; move, 50;";

stringses = str.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(s => s.Split(new[] {','}))
               .ToArray();