如何在 LINQ 中执行 String.Replace?

2024-05-12

这是我正在尝试做的事情,但没有成功。我想打电话from x in list1 and join y in list2 where regex.Match(x.Value).Success。完成这些步骤后我需要打电话String.Replace两次x.Value。然后致电on and select运营商。我希望它看起来像第二个例子。如何才能实现这一目标?

我的列表如下所示:

list1              list2
Name    Value      Name    Value
item.1  $(prod1)   prod1   prodVal1
item.2  $(prod2)   prod2   prodVal2
item.3  prod3      prod3   prodVal3

我的列表应该是这样的:

updatedList         
Name    Value     
item.1  prodVal1   
item.2  prodVal2       
item.3  prod3      

示例1(这是我目前拥有的):

foreach (var x in list1)
{
    Match match = reg.Match(x.Value);
    if (match.Success)
    {
        x.Value = x.Value.Replace("$(", "");
        x.Value = x.Value.Replace(")", "");
    }
}

var commonItems = from x in list1
                  join y in list2
                  on x.Value equals y.Name
                  //where regex.Match(x.Value).Success
                  select new { Item = x, NewValue = y.Value };

foreach (var x in commonItems)
{
    x.Item.Value = x.NewValue;
}

示例2:

var commonItems = from x in list1
                  join y in list2
                  where regex.Match(x.Value).Success
                  //do x.Value.Replace("$(", "")
                  //do x.Value.Replace(")", "")
                  //then call
                  on x.Value equals y.Name
                  select new { Item = x, NewValue = y.Value };

foreach (var x in commonItems)
{
    x.Item.Value = x.NewValue;
}

如果我理解正确的话你想要的是使用let在您的查询中:

var commonItems = from x in list1
                  join y in list2
                  let newX = x.Value.Replace("$(", "").Replace(")", "")
                  where regex.Match(x.Value).Success
                 &&  newX == y.Name
                  select new { Item = newX, NewValue = y.Value };
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 LINQ 中执行 String.Replace? 的相关文章

随机推荐