对于带有索引器(数组或列表)的集合,您可以在一个循环中完成
for(var i = 0; i < values.Length; i++)
{
if (i > 0 && values[i - 1] == "$id")
{
values[i - 1] = values[i];
}
}
对于任何类型的集合,您都可以使用枚举器将集合“循环”一次,并且可以访问当前和上一个元素。
下面的方法也支持"$id" 的多次出现。
public static IEnumerable<string> ReplaceTemplateWithNextValue(
this IEnumerable<string> source,
string template
)
{
using (var iterator = source.GetEnumerator())
{
var previous = default(string);
var replaceQty = 0;
while (iterator.MoveNext())
{
if (iterator.Current == "$id") replaceQty++;
if (previous == "$id" && iterator.Current != "$id")
{
for (var i = 0; i < replaceQty; i++) yield return iterator.Current;
replaceQty = 0;
}
if (iterator.Current != "$id") yield return iterator.Current;
previous = iterator.Current;
}
if (previous == $"$id")
{
for (var i = 0; i < replaceQty; i++) yield return previous;
}
}
}
用法
var list = new List<string>() { "test", "$id", "central" };
var replaced = list.ReplaceTemplateWithNextValue("$id");
// => { "test", "central", "central" }
支持的案例:
[Fact]
public void TestReplace()
{
ReplaceId(Enumerable.Empty<string>()).Should().BeEmpty(); // Pass
ReplaceId(new[] { "one", "two" })
.Should().BeEquivalentTo(new[] { "one", "two" }); // Pass
ReplaceId(new[] { "$id", "two" })
.Should().BeEquivalentTo(new[] { "two", "two" }); // Pass
ReplaceId(new[] { "one", "$id", "two" })
.Should().BeEquivalentTo(new[] { "one", "two", "two" }); // Pass
ReplaceId(new[] { "one", "two", "$id" })
.Should().BeEquivalentTo(new[] { "one", "two", "$id" }); // Pass
Replace(new[] { "one", "$id", "$id" })
.Should().BeEquivalentTo(new[] { "one", "$id", "$id" }); // Pass
}