[英]How to do a String.Replace in LINQ?
這是我想要做的但沒有成功。 我想from x in list1
調用並join y in list2 where regex.Match(x.Value).Success
。 在這些步驟之后,我需要在x.Value
上調用String.Replace
兩次。 然后調用on
和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 };
你確定需要Regex.Match
嗎? 你可以在不使用它的情況下獲得相同的結果,無論如何我添加了兩個版本......
在1°版本中,您可以使用簡單的If語句來檢查值是否已更改
NewValue = x.Value != x1 ? y.Value: x.Value
示例代碼
給這個班級
class MyClass
{
public string Name { get; set; }
public string Value { get; set; }
}
。
添加項目
var list1 = new List<MyClass>();
list1.Add(new MyClass { Name = "item.1", Value = "$(prod1)" } );
list1.Add(new MyClass { Name = "item.2", Value = "$(prod2)" });
list1.Add(new MyClass { Name = "item.3", Value = "prod3" });
var list2 = new List<MyClass>();
list2.Add(new MyClass { Name = "prod1", Value = "prodVal1" });
list2.Add(new MyClass { Name = "prod2", Value = "prodVal2" });
list2.Add(new MyClass { Name = "prod3", Value = "prodVal3" });
得到共同的清單
var q = from x in list1
let x1 = x.Value.Replace("$(", "").Replace(")", "")
join y in list2 on x1 equals y.Name
select new {
Item = x.Name,
NewValue = x.Value != x1 ? y.Value: x.Value
};
foreach (var s in q)
{
Console.WriteLine(s.Item + " " + s.NewValue);
}
結果
item.1 prodVal1
item.2 prodVal2
item.3 prod3
PS :我認為你不需要正則Regex
,但萬一這個版本可以使用它。
var q = from x in list1
let x1 = x.Value.Replace("$(", "").Replace(")", "")
join y in list2 on x1 equals y.Name
select new
{
Item = x.Name,
NewValue = Regex.Match(x.Value, x1).Success ? x.Value : y.Value
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.