拆分for循环,替换为lambda表达式

时间:2016-12-11 11:06:30

标签: c# string for-loop lambda split

我有一个字符串q.ACBValue,其中包含&#34; v1,v2,v4&#34; &#34; v3,v5&#34; < / strong>即可。我想将以下代码转换为更整洁的lambda表达式

 string[] list = q.ACBValue.Split(',');

 for (int i = 0; i < list.Count(); i++)
 {
     q.ACBOption = q.ACBOption.Replace("value='"+ list[i] + "' ", "value='" + list[i] + "' checked=\"checked\""); 
 }

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

q.ACBValue.Split(',')
    .Select(s => new
    {
        Search = "value='" + s + "' ",
        Replace = "value='" + s + "' checked=\"checked\""
    })
    .ToList()
    ForEach(tuple => 
        qACBOption = q.ACBOption.Replace(tuple.Search, tuple.Replace));

此解决方案使用ForEach类的List<T>方法。要使其可见,您必须通过显式调用扩展方法ToList来将前一个序列转换为列表。

还有另一种方法,您可以使用Aggregate扩展方法聚合结果:

q.ACBOption =
    q.ACBValue.Split(',')
        .Select(s => new
        {
            Search = "value='" + s + "' ",
            Replace = "value='" + s + "' checked=\"checked\""
        })
        .Aggregate(
            q.ACBOption, 
            (res, tuple) => res.Replace(tuple.Search, tuple.Replace));