替换字符串列表中的字符串

时间:2021-02-19 03:49:35

标签: c# .net list linq replace

我想用下一个列表项字符串替换字符串 "$id"。例如,如果列表是

var list = new List<string>()
{
    "test",
    "$id",
    "central",
};

那么列表就会变成

"test"
"central"
"central"

同样,如果列表只有 1 个项目 "$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;
 }

这是正确的做法还是有更有效的做法。

任何帮助或建议将不胜感激。

2 个答案:

答案 0 :(得分:2)

这对我有用(前提是列表至少有一个元素):

list =
    list
        .Skip(1)
        .Zip(list, (x1, x0) => x0 == "$id" ? x1 : x0)
        .Append(list.Last())
        .ToList();

答案 1 :(得分:1)

对于带有索引器的集合(数组或列表),您可以在一个循环中完成

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
}