[英]Replace string in the list of string
我想用下一个列表项字符串替换字符串"$id"
。 例如,如果列表是
var list = new List<string>()
{
"test",
"$id",
"central",
};
那么列表将变为
"test"
"central"
"central"
类似地,如果列表只有一项"$id"
或"$id"
是列表中的最后一项,则它不会被任何内容替换。
我创建了以下逻辑
int index = list.FindIndex(x => x == "$id");
if (index < list.Count()-1)
{
var newList = list.Select(x => x.Replace(list[index], list[index+1])).ToList();
list = newList;
}
这是正确的方法还是有更有效的方法。
任何帮助或建议将不胜感激。
这对我有用(前提是列表至少有一个元素):
list =
list
.Skip(1)
.Zip(list, (x1, x0) => x0 == "$id" ? x1 : x0)
.Append(list.Last())
.ToList();
对于带有索引器(数组或列表)的 collections,您可以在一个循环中完成
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
}
这对我来说似乎更简单,但也许不起作用,或者速度很慢?
int index = list.IndexOf("$id");
list.RemoveAt(index);
list.Insert(index, list[index]); //list[index] was list[index+1] before RemoveAt
// With error checks:
int index = list.IndexOf("$id");
if (index == -1) return; // or return error;
list.RemoveAt(index);
if (index >= list.Count-1) return; // or return error;
list.Insert(index, list[index+1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.