日期:2014-05-17  浏览次数:20880 次

用linq实现字符串分割
接上一个帖子


这个方法在有两个及以上的时候有效,得到
str1=col1,col2 
str2='1','2'
var strArr = "col1,1,col2,2";

var str1 = strArr.Split(',').Where((x, i) => i % 2 == 0).Aggregate((x, y) => y = x + "," + y);
var str2 = strArr.Split(',').Where((x, i) => i % 2 == 1).Aggregate((x, y) => y = "'" + x + "','" + y + "'");



但是若变成var strArr = "col1,1";
用上面的方法
则变成:str1=col1
str2=1(少了单引号)

------解决方案--------------------
 var strArr = "col1,1".Split(new string[] { ",", "," }, StringSplitOptions.RemoveEmptyEntries).Select((t, index) => new { value = t, index = index });
            string str2 = string.Join(",", strArr.Where(t => t.index % 2 == 1).Select(t =>"'"+ t.value+"'").ToList());